c# - How to handle many to many same table (User) in ASP.Net MVC 5 - Fluent API -
i learning asp.net mvc 5 , stuck 1 basic db design. so, have 1 user can refer many person in job also, many person can apply referred. have created 2 roles , of taken care. now, have on class called referral keep track of every instance of referral needs done.
referral model:
public class referral { [key] public int referralid { get; set; } public company company { get; set; } public int companyid { get; set; } public applicationuser user { get; set; } public string candidateid { get; set; } // application user id of person asking referral public string referrerid { get; set; } // application user id of person referring candidate }
applicationuser model
public class applicationuser : identityuser { public icollection<referral> referrals { get; set; } // rest prop removed brevity sake }
now, suppose a(referrer) refers b(candidate). table row below.
referralid companyid candidateid referrerid 1 1 b
so, far good. want establish fk relationship on referral table. new fluent api tried below.
// 1 candidate can have many referrals dbmodelbuilder.entity<applicationuser>() .hasmany(u => u.referrals) .withrequired(u => u.user) .hasforeignkey(u => u.candidateid) .willcascadeondelete(false); //one referrar can have many referrals dbmodelbuilder.entity<applicationuser>() .hasmany(u => u.referrals) .withrequired(u => u.user) .hasforeignkey(u => u.referrerid);
but ef respects 1 relationship. why both foreign key relationhip not getting set. if comment out 1 other works, , vice versa. keeping them shown never works.
expected behaviour: expected have 2 fk relationship. once have can work accordingly. please guide me here. new this.
as @slaks mentioned in comments, in order have two relationships, need two havigation properties (one each fk).
so in one side replace referrals
property this:
public class applicationuser : identityuser { // ... public icollection<referral> referrerof { get; set; } public icollection<referral> candidateof { get; set; } }
at many side replace user
property with:
public class referral { // ... public applicationuser candidate { get; set; } public applicationuser referrer { get; set; } }
and correlate them 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 navigation properties don't matter correlate them correctly.
Comments
Post a Comment