[英]Entity Framework: Add child record to and existing parent
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. 该custOrder包含一个父级(已经存在)和一个需要添加的新子级记录。 Eg 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. 请指教。
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;
}
You need to tell EF that the child itself was actually added. 您需要告诉EF该孩子本身已被添加。 It won't assume from the parent that something needs to be added when the EntityState is set to Modified.
当EntityState设置为Modified时,它不会从父级假设需要添加某些内容。 You need to Add that new child record to the context, and then run the save.
您需要将该新的子记录添加到上下文中,然后运行保存。
Assuming OrderItem
class as your child: 假设
OrderItem
类为您的孩子:
dbContext.OrderItems.Add(myNewOrderItem);
dbContext.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.