Friday, June 7, 2013

Multiple foreign keys within same table using CodeFrist Enitty Framework and Fluent API

This example shows how to work with multiple foreign key referred to the same table using CodeFirst Entity Framework (Inverse Navigation Properties 
)

Parent Table (Branch) has two foreign keys (Primary Contact and Secondary Contact) referring to the Child Table (Contact).


Branch
BranchIDguid
Branch Namevarchar
PrimaryContactIDguid,null
SecondaryContatIDguid,null



Contact
ContactIDguid
Firstnamevarchar
LastNamevarchar
Addressvarchar
Genderchar
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


 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 :)