Configure Many-to-Many Relationships Using Fluent API

In this blog, I’ll show you how to configure Many-to-Many relationships between Order and Product entities as shown below:

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 ICollection < Product > Products  
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23.     public Order()  
  24.     {  
  25.     }  
  26. }  
Product.cs
  1. public class Product  
  2. {  
  3.     public int ProductId  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string ItemName  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public int CostPerUnit  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public int NumerInStock  
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23.     public ICollection < Order > Orders  
  24.     {  
  25.         get;  
  26.         set;  
  27.     }  
  28.     public Product()  
  29.     {  
  30.     }  
  31. }  
Now, you can configure many-to-many relationships as follows:
  1. protected override void OnModelCreating(DbModelBuildermodelBuilder)  
  2. {  
  3.     modelBuilder.Entity < Order > ()  
  4.         .HasMany < Product > (p => p.Products)  
  5.         .WithMany(o => o.Orders)  
  6.         .Map(op =>  
  7.         {  
  8.             op.MapLeftKey("OrderId");  
  9.             op.MapRightKey("ProductId");  
  10.             op.ToTable("OrderDetails");  
  11.         });  
  12. }  
As you can see above, the code that I wrote will create a new table named OrderDetails with OrderId, and ProductId properties.