In this blog, I’ll show you how to configure Many-to-Many relationships between Order and Product entities as shown below:
Order.cs
- public class Order
- {
- public int OrderId
- {
- get;
- set;
- }
- public DateTime Date
- {
- get;
- set;
- }
- public int price
- {
- get;
- set;
- }
- public ICollection < Product > Products
- {
- get;
- set;
- }
- public Order()
- {
- }
- }
Product.cs
- public class Product
- {
- public int ProductId
- {
- get;
- set;
- }
- public string ItemName
- {
- get;
- set;
- }
- public int CostPerUnit
- {
- get;
- set;
- }
- public int NumerInStock
- {
- get;
- set;
- }
- public ICollection < Order > Orders
- {
- get;
- set;
- }
- public Product()
- {
- }
- }
Now, you can configure many-to-many relationships as follows:
- protected override void OnModelCreating(DbModelBuildermodelBuilder)
- {
- modelBuilder.Entity < Order > ()
- .HasMany < Product > (p => p.Products)
- .WithMany(o => o.Orders)
- .Map(op =>
- {
- op.MapLeftKey("OrderId");
- op.MapRightKey("ProductId");
- op.ToTable("OrderDetails");
- });
- }
As you can see above, the code that I wrote will create a new table named OrderDetails with OrderId, and ProductId properties.