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

非常感謝你! :) –