Reputation: 2553
I need to add a child record to and existing parent.
I call the following methods
_handler.Update(custOrder);
_handler.Save();
public TEntity Update(TEntity entity)
{
Entities.Attach(entity);
DataContext.Entry(entity).State = EntityState.Modified;
return entity;
}
and
public void Save() {
try
{
base.SaveChanges();
}
catch (Exception e) { }
}
The custOrder contains the parent (which already exists) and a new child record that needs to be added. E.g. Adding an order item for an existing order.
However when I execute this the child does not get added.
I am not sure how specify that the parent has not changed but a child was added
Please advice.
Upvotes: 3
Views: 7614
Reputation: 2553
I finally got the answer it was a bit subtle have to admit, The parent entity needed to be added instead of attached and the state set to modified afterwards.
public TEntity Update(TEntity entity)
{
Entities.Add(entity);
DataContext.Entry(entity).State = EntityState.Modified;
return entity;
}
Upvotes: 3
Reputation: 16137
You need to tell EF that the child itself was actually added. It won't assume from the parent that something needs to be added when the EntityState is set to Modified. You need to Add that new child record to the context, and then run the save.
Assuming OrderItem
class as your child:
dbContext.OrderItems.Add(myNewOrderItem);
dbContext.SaveChanges();
Upvotes: 2