I’m trying to use the awsome EF5 with code first – where I need to make a many-to-many table with extra fields.
I’ve got a products table, orders table and need a table of products that are in orders with a “size” field.
What I’ve done is created a new class of “ProductOrder” that is the connection table between them, and made a reference.
It WORKS when creating a new order, but is not working when fetching an order – it doesn’t get the connected orders (that are present in the DB after the insertion).
Ideas why? 🙂
My Classes are:
public class Order
{
public int ID { get; set; }
...
public ICollection<ProductOrder> Products { get; set; }
public Order()
{
Products = new HashSet<ProductOrder>();
}
}
public class Product
{
public int ID { get; set; }
public ICollection<ProductOrder> Orders { get; set; }
}
public class ProductOrder
{
public int ID { get; set; }
public int ProductID { get; set; }
public int OrderID { get; set; }
public int Size { get; set; }
[ForeignKey("OrderID")]
public Order order { get; set; }
[ForeignKey("ProductID")]
public Product product { get; set; }
}
and in onModelCreating
modelBuilder.Entity<Order>()
.HasMany(p => p.Products)
.WithRequired(o => o.order)
.HasForeignKey(o => o.OrderID);
modelBuilder.Entity<Product>()
.HasMany(o => o.Orders)
.WithRequired(p => p.product)
.HasForeignKey(p => p.ProductID);
Your navigational properties need to be virtual