【问题标题】:Can I have an self referencing inverse navigation property with optional foreign key?我可以有一个带有可选外键的自引用反向导航属性吗?
【发布时间】:2015-09-16 17:06:09
【问题描述】:

ASP.NET Identity 开发人员应该认识到我重命名的 ApplicationUser 类(现在称为 User)派生自 IdentityUser,它具有基于 Guid 的 Id 属性。在我的用户类中,我有一个可选的自引用外键(公共 Guid?ManagerId)和一个简单的匹配导航属性(公共用户管理器)。所有这些都有效。我的问题是我想要第二个导航属性(DirectlyManagedUsers),但我不知道如何对其进行注释,以使其包含该用户的直接管理用户的集合。我将不胜感激。

这是我的用户类:

public class User : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager, string authenticationType)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
        return userIdentity;
    }

    public User() : base()
    {
        DirectlyManagedUsers = new List<User>();
    }

    public User(string userName) : base(userName)
    {
        DirectlyManagedUsers = new List<User>();
    }

    [ForeignKey(nameof(Manager))]
    public Guid? ManagerId { get; set; }

    [ForeignKey(nameof(ManagerId))]
    public User Manager { get; set; }

    [InverseProperty(nameof(Manager))]
    public ICollection<User> DirectlyManagedUsers { get; set; }
}

我在生成模型时遇到以下错误:

One or more validation errors were detected during model generation:

User_DirectlyManagedUsers_Source_User_DirectlyManagedUsers_Target: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'ManagerId' on entity 'User' does not match the type of property 'Id' on entity 'User' in the referential constraint 'User_DirectlyManagedUsers'. The type of property 'ManagerId' on entity 'User' does not match the type of property 'Id' on entity 'User' in the referential constraint 'User_DirectlyManagedUsers'.

我知道这与 ManagerId 的可为空的 Guid 类型有关。那我该怎么办?

【问题讨论】:

  • 如果您更喜欢使用Guid,您可以随时更改 ID 类型。我回答了questions 中的couple,这可能会对您有所帮助。

标签: entity-framework asp.net-identity-2


【解决方案1】:

好的,我知道出了什么问题。我使用可为空的 Guid (Guid?) 作为我的 ManagerId 的类型。实际上,在 ASP.NET Identity 框架中,预构建的 Entity Framework IdentityUser 类对其 Id 属性使用字符串类型。此字符串属性设置为使用 .ToString() 转换为字符串的新 Guid 的值。一旦我弄清楚了(并且因为我知道该字符串可以为空),我只需将我的 ManagerId 属性的类型更改为字符串并且一切正常。所以我的问题是通过在身份框架中找出正确的类型来解决的,而不是通过为实体框架以不同的方式注释属性。如果 Id 不是可空类型,我很好奇是否有人可以回答原始问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多