Here is simplified model of my MySQL database (model first):
I mapped it via Entity Framework v6.1.3. I have
dataContext
object to make database queries.
OrderProductsProduct1
is table to make foreign key connections, here is EF auto generated class:
public partial class OrderProductsProduct1
{
public int ID { get; set; }
public int OrderProductsID { get; set; }
public int Product1ID { get; set; }
public decimal Width { get; set; }
public virtual OrderProducts OrderProducts { get; set; }
public virtual Product1 Product1 { get; set; }
}
I'm confused how to add new objects to database, which has two one to many foreign keys. For example how to properly add Order
object with few Product1
objects connected via OrderProducts
and OrderProductsProduct1
tables.
So far I was trying to make a List
of OrderProducts
, where each OrderProduct
has another List
with OrderProductsProduct1 and 2
. To OrderProductsProduct1 and 2
I was adding Products1 and 2
. Finally OrderProducts
was bound to Order
with orderProducts.Order = newOrder
and then dataContext.Add(newOrder)
. But this causes Entity Framework exceptions.
Do I have to create objects from the lowest level (Client, Product1, Product2), add them to database with dataContext.Add()
, to get their ID's and then bound them with higher level objects (Order) and so on until the highest level (OrderProductsProduct1 and 2)? This approach omits Entity Framework and makes hard to revert changes in case of errors.