This example shows how to work with multiple foreign key referred to the same table using CodeFirst Entity Framework (Inverse Navigation Properties
)
When configuring in the fluent API below shown coding is used.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Branch>().HasOptional(b => b.PrimaryContact).WithMany(a => a.PrimaryContactFor).HasForeignKey(b=>b.PrimaryContactID);
modelBuilder.Entity<Branch>().HasOptional(b => b.SecondaryContact).With Many (a => a.ScondaryContactFor).HasForeignKey(b=>b.ScondaryContactID);
}
Happy Coding :)
)
Parent Table (Branch) has two foreign keys (Primary Contact and Secondary Contact) referring to the Child Table (Contact).
Branch | |
BranchID | guid |
Branch Name | varchar |
PrimaryContactID | guid,null |
SecondaryContatID | guid,null |
Contact | |
ContactID | guid |
Firstname | varchar |
LastName | varchar |
Address | varchar |
Gender | char |
First of all we need to create the Branch Class
public class Branch
{
public Guid BranchID { get; set; }
public string BranchName { get; set; }
public Nullable<Guid> PrimaryContactID { get; set; }
public Nullable<Guid> ScondaryContactID{ get; set; }
public Contact PrimaryContact { get; set; }
public Contact SecondaryContact { get; set; }
}
Then creating the Contact Class
Then creating the Contact Class
public class Contact
{
public Guid ContactID { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; } public ICollection<Branch> PrimaryContactFor { get; set; }
public ICollection<Branch> ScondaryContactFor{ get; set; }
}
When configuring in the fluent API below shown coding is used.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Branch>().HasOptional(b => b.PrimaryContact).WithMany(a => a.PrimaryContactFor).HasForeignKey(b=>b.PrimaryContactID);
modelBuilder.Entity<Branch>().HasOptional(b => b.SecondaryContact).With Many (a => a.ScondaryContactFor).HasForeignKey(b=>b.ScondaryContactID);
}
Happy Coding :)