Reputation: 2054
I'm fairly new to entity framework and patterns. How would I insert data into a child table?
I inserted the information into the parent table. Do I have to return the identity of the row and then issue another insert?
User Table and User Role.
I've been trying to find a solution for a day now, but I think its because I'm searching the wrong results. My structure is set up using Unit of Work/Repository Pattern.
Any help would be helpful. Thanks!
Upvotes: 1
Views: 880
Reputation: 218732
Get the Parent object. Add the child record to it's navigation property.
something like this
int orderId=33;
var parent=dbContext.Orders.Where(x=>x.Id==orderId);
parent.Details.Add(new OrderDetail{ Quantity=4, ItemId=37});
parent.Details.Add(new OrderDetail{ Quantity=2, ItemId=48});
dbContext.SaveChanges();
Assuming Order is your Master entity and Detail is your child entity and dbContext is your DBContext class object.
EDIT : If you are adding it together,
Order parent=new Order { CustomerId=35, Discount=43.63 };
parent.Details.Add(new OrderDetail{ Quantity=4, ItemId=37});
parent.Details.Add(new OrderDetail{ Quantity=2, ItemId=48});
dbContext.Orders.Add(parent);
dbContext.SaveChanges();
Upvotes: 3