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

后端 未结 1 852
刺人心
刺人心 2021-01-27 03:48

I am learning ASP.Net MVC 5 and I am stuck with one basic DB Design. So, I have one User which can refer many person in job Also, many person can apply to get themselves Referr

1条回答
  •  生来不讨喜
    2021-01-27 04:08

    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 ReferrerOf { get; set; }
        public ICollection 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()
        .HasMany(u => u.CandidateOf) // <--
        .WithRequired(r => r.Candidate) // <--
        .HasForeignKey(r => r.CandidateId)
        .WillCascadeOnDelete(false);
    
    modelBuilder.Entity()
        .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.

    0 讨论(0)
提交回复
热议问题