Configure One-to-Many Relationships Using Fluent API

So, let’s configure one-to-many relationships using Customer and Order entities

Customer.cs

  1. public class Customer  
  2. {  
  3.     public int CustomerId  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string CustomerName  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public string CustomerEmail  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public int OrderId  
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23.     public virtual Order Order  
  24.     {  
  25.         get;  
  26.         set;  
  27.     }  
  28.     public Customer()  
  29.     {  
  30.     }  
  31. }  
Order.cs
  1. public class Order  
  2. {  
  3.     public int OrderId  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public DateTime Date  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public int price  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public virtual ICollection < Customer > Customer  
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23.     public Order()  
  24.     {  
  25.     }  
  26. }  
Now, you can configure one-to-many relationships as shown below:
  1. protected override void OnModelCreating(DbModelBuildermodelBuilder)  
  2. {  
  3.     // one-to-many  
  4.     modelBuilder.Entity < Customer > ().HasRequired < Order > (o => o.Order)  
  5.         .WithMany(c => c.Customer);  
  6. }  
Now, I would like to add, suppose if customer and order entities don’t follow code first conventions for foreign key. For example, the customer class includes different foreign key (ex: ordId) for order entity. In this case you will proceed as follows:
  1. protected override void OnModelCreating(DbModelBuildermodelBuilder)  
  2. {  
  3.     //one-to-many  
  4.     modelBuilder.Entity < Customer > ()  
  5.         .HasRequired < Order > (o => o.Order)  
  6.         .WithMany(c => c.Customer)  
  7.         .HasForeignKey(o => o.OrdId);  
  8. }  
Before finishing, I want share with yo, how to make Nullable foreign key for one-to-many relationships. For doing this, you should write the following code as shown below:
  1. protected override void OnModelCreating(DbModelBuildermodelBuilder)  
  2. {  
  3.     modelBuilder.Entity < Customer > ()  
  4.         .HasOptional < Order > (o => o.Order)  
  5.         .WithMany(c => c.Customer);  
  6. }  
In the next blog, we learn how to configure many-to-many relationships using Fluent API.

 

Ebook Download
View all
Learn
View all