1

我想要一个用户有很多追随者和他们正在关注的人。EF核心自我参照

现在即时我得到这个错误。

无法确定类型为'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); 
} 

回答

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); 
} 
+0

非常感谢你! :) –