Hi every body !
I have a question about Relationship Many to many using EF Code First fluent API in MVC.
Normally, We can easily create many to many relationship between two tables (for example
Student table and
Course table) by the following:
modelBuilder.Entity<Student>()
.HasMany<Course>(s => s.Courses)
.WithMany(c => c.Students)
.Map(cs =>
{
cs.MapLeftKey("StudentRefId");
cs.MapRightKey("CourseRefId");
cs.ToTable("StudentCourse");
});
But in my case, I have 3 tables
Order,
Product and
OrderDetail (similar to the NorthWind sample database). So how can I create relationship many to many between
Product Table and
Order Table by using table
OrderDetail.
And here are my Order class and Product class:
public class OrderMapping : EntityTypeConfiguration<Order>
{
public OrderMapping()
{
HasKey(o => o.OrderID);
Property(o => o.OrderID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(o => o.CustomerID).IsRequired();
Property(o => o.OrderDate).IsRequired();
Property(o => o.RequireDate).IsRequired();
Property(o => o.ShippedDate).IsRequired();
Property(o => o.ShipVia).IsRequired();
Property(o => o.Freight).IsRequired();
Property(o => o.ShipAddress).IsRequired();
Property(o => o.ShipCity).IsRequired();
Property(o => o.ShipRegion).IsRequired();
Property(o => o.ShipCountry).IsRequired();
Property(o => o.ShipPostalCode).IsRequired();
Property(o => o.ShipName).IsRequired();
ToTable("Order");
}
}
public class ProductMapping : EntityTypeConfiguration<Product>
{
public ProductMapping()
{
HasKey(pro => pro.ProductID);
Property(pro => pro.ProductName).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(pro => pro.CategoryID).IsRequired();
Property(pro => pro.QuantityPerUnit).IsRequired();
Property(pro => pro.UnitPrice).IsRequired();
Property(pro => pro.UnitsInStock).IsRequired();
Property(pro => pro.UnitsOnOrder).IsRequired();
Property(pro => pro.ReorderLevel);
Property(pro => pro.Discontinued);
ToTable("Product");
}
}
What should i do in OrderDetail class ?
public class OrderDetailMapping : EntityTypeConfiguration<OrderDetail>
{
public OrderDetailMapping()
{
???
ToTable("OrderDetail");
}