Multiple foreign keys within same table using code frist enitty framework and navigation property

Multiple foreign keys within same table using code frist enitty framework and navigation property in parent table

In this example show you, how to work with multiple foreign key reference to the same table using Code First Entity Framework and Navigation Property

First we need to create a two table User and contactNumber, where User table is primary table and contactNumber is a secondary table

public class User

{

     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

     public int Id { get; set; }


     public string Name { get; set; }
     public virtual ICollection<ContactNumbers> contactNumbers { get; set; }
}



public class ContactNumber

{

     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

     public long Id { get; set; }

     public int UserId { get; set; }  
     [ForeignKey("UserId")]

     public virtual User user { get; set; }


     public int? CreatedById { get; set; }

     public int? ModifiedById { get; set; }


     [ForeignKey("CreatedById")]

     public virtual User CreatedBy { get; set; }

    [ForeignKey("ModifiedById")]

    public virtual User ModifiedBy { get; set; }

}

In User table Id is a primary key when UserId, CreatedById, ModifiedById is foreign key in child table with user table

I created one navigation property in User table as like below
 
public virtual ICollection<ContactNumbers> contactNumbers { get; set; }

But in above case, Occur some conflict with child table (ContactNumber) because of navigation property can not be identified how it can be associated with child table(ContactNumber)

The solution is that configuring in the fluent API below shown coding is used
 
protected override void OnModelCreating(DbModelBuilder modelBuilder)

{

         modelBuilder.Entity<ContactNumber>()

                              .HasRequired<User>(s => s.user)

                              .WithMany(s => s.userContactNumbers)

                              .HasForeignKey(s => s.UserId);



        base.OnModelCreating(modelBuilder);

}

 

Comments

Popular posts from this blog

Get OAuth 2.0 access token of Paypal using HttpClient in c#

Generics method using interface in c#