EF核心自我参考

时间:2017-07-26 16:08:17

标签: c# asp.net-mvc entity-framework asp.net-core entity-framework-core

我希望用户有很多关注者和他们关注的很多人​​。

现在我得到了这个错误。

  

无法确定“ICollection”类型的导航属性“ApplicationUser.Following”所代表的关系。手动配置关系,或从模型中忽略此属性。

// ApplicationUser File.
public class ApplicationUser : IdentityUser<int>
{
    // OTHER PROPERTIES ABOVE
    public virtual ICollection<ApplicationUser > Following { get; set; }
    public virtual ICollection<ApplicationUser > Followers { get; set; }
}

// Context File
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
}

1 个答案:

答案 0 :(得分:5)

你需要一个额外的课来完成它。这样的事情应该有效:

public class ApplicationUser : IdentityUser<int>
{
    public string Id {get; set;}
    // OTHER PROPERTIES ABOVE
    public virtual ICollection<UserToUser> Following { get; set; }
    public virtual ICollection<UserToUser> Followers { get; set; }
}

public class UserToUser 
{
    public ApplicationUser User { get; set;}
    public string UserId { get; set;}
    public ApplicationUser Follower { get; set;}
    public string FollowerId {get; set;}
}

// Context File
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<UserToUser>()
        .HasKey(k => new { k.UserId, k.FollowerId });

    modelBuilder.Entity<UserToUser>()
        .HasOne(l => l.User)
        .WithMany(a => a.Followers)
        .HasForeignKey(l => l.UserId);

    modelBuilder.Entity<UserToUser>()
        .HasOne(l => l.Follower)
        .WithMany(a => a.Following)
        .HasForeignKey(l => l.FollowerId);
}