How to handle many to many same table (User) in ASP.Net MVC 5 - Fluent API

对着背影说爱祢 提交于 2019-12-02 03:25:47

As @SLaks mentioned in the comments, in order to have two relationships, you need two havigation properties (one for each FK).

So in the one side replace Referrals property with something like this:

public class ApplicationUser : IdentityUser
{
    // ...
    public ICollection<Referral> ReferrerOf { get; set; }
    public ICollection<Referral> CandidateOf { get; set; }
}

at many side replace the User property with:

public class Referral
{
    // ...
    public ApplicationUser Candidate { get; set; }
    public ApplicationUser Referrer { get; set; }
}

and correlate them with fluent API:

modelBuilder.Entity<ApplicationUser>()
    .HasMany(u => u.CandidateOf) // <--
    .WithRequired(r => r.Candidate) // <--
    .HasForeignKey(r => r.CandidateId)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<ApplicationUser>()
    .HasMany(u => u.ReferrerOf) // <--
    .WithRequired(r => r.Referrer) // <--
    .HasForeignKey(r => r.ReferrerId);

The names of the navigation properties don't really matter as soon as you correlate them correctly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!