'How do insert more than one row into a table using Entity Framework when one column is a foreign key?
Please help me. I can't find this anywhere. I want to do this with Entity framework when inserting:
- Add 1 row to table tParent
- Add 4 rows to table tChildren.
tChildren has a column that is a FK of tParent called ParentID.
I'm on 4.0 framework.
Solution 1:[1]
You will have to add the children to the parent using a loop but need to call save changes once, something like as follows, say the parent is Order and child is called OrderItem
public void AddOrder(OrderDto orderToAdd)
{
var newOrder = Order.CreateOrder(orderToAdd.OrderID, .....); //set all other non nullable attributes
neworder.OrderDate = orderToAdd.OrderDate;
//set other properties
'
'
//then add the order items to the newOrder
//note orderToAdd.OrderItemsDto is the ChildList
foreach (OrderItemDto o in orderToAdd.OrderItemsDto)
{
var orderItem = OrderItem.CreateOrderItem(orderToAdd.OrderID, o.OrderItemID); //set all other non nullable attributes
orderItem.OrderQuantity = o.OrderQuantity;
//set other properties
'
'
newOrder.OrderItems.Add(orderItem);
}
context.AddToOrders(newOrder);
context.SaveChanges();
}
Solution 2:[2]
The key is that you have navigational properties setup on the entities.
tParent should have a navigational property called tChildrens, and (optionally), tChildren should have a navigational property called tParent.
The multiplicity should be tParent 1..* tChildren.
With that in mind, this should do the trick:
var parent = new tParent();
var child1 = new tChild();
var child2 = new tChild();
// set properties you need, etc etc
parent.tChildrens.Add(child1);
parent.tChildrens.Add(child2);
context.SaveChanges();
EF is smart enough to add the parent, grab the identity, then insert the children with the FK set to the identity just created.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | halfer |
