是否再次将父实体附加到上下文并更新它应该更新子实体?我错过了什么吗?
或者我是否应该为子实体编写更新 EF 逻辑(在 DAL 中)?
这是我的示例代码模型:
ChildEntity entityChild;
if (ParentEntity.ChildEntity.SingleOrDefault() != null)
entityChild = ParentEntity.ChildEntity.SingleOrDefault();
else
{
entityChild = new ChildEntity();
ParentEntity.ChildEntity.Add(entityChild);
}
entityChild.ColumnA= txtA.Text;
entityChild.ColumnB= txtB.Text;
// Send entityParent for update
_objParent.Update(entityParent)
_objParent.Update() 代码:
context.vouchers.Attach(entityParent);
ObjectStateEntry objectState = context.ObjectStateManager.GetObjectStateEntry(entityParent);
objectState.ChangeState(System.Data.EntityState.Modified);
context.SaveChanges();
更新(父加载代码示例)
public ParentEntity GetById(int id)
{
using (var context = new DBEntities())
{
ParentEntity _entity = context.ParentEntity
.Include("ChildEntity")
.Where(e => e.parent_id == id);
return (ParentEntity)_entity.SingleOrDefault()
}
}