不完全是你的方式,因为我使用带有状态标志的 POCO,但它也可以应用于生成的实体。这是一种管理父实体和子实体状态的递归方法。这是Parent 实体的状态管理器类:
public partial class ParentStateManager : IStateManager<Parent, MyObjContext>
{
private IStateManager<Child, MyObjContext> _ChildStateManager = new ChildStateManager();
public void ChangeState(Parent m, MyObjContext ctx)
{
if (m == null) return;
ctx.Parents.Attach(m);
if (m.IsDeleted)
{
ctx.ObjectStateManager.ChangeObjectState(m, System.Data.EntityState.Deleted);
}
else
{
if (m.IsNew)
{
ctx.ObjectStateManager.ChangeObjectState(m, System.Data.EntityState.Added);
}
else
{
if (m.IsDirty)
{
ctx.ObjectStateManager.ChangeObjectState(m, System.Data.EntityState.Modified);
}
}
}
SetRelationsState(m, ctx);
}
private void SetRelationsState(Parent m, MyObjContext ctx)
{
foreach (Child varChild in m.Children.Where(p => !p.IsDeleted))
{
_ChildStateManager.ChangeState(varChild, ctx);
}
while (m.Children.Where(p => p.IsDeleted).Any())
{
_ChildStateManager.ChangeState(m.Children.Where(p => p.IsDeleted).LastOrDefault(), ctx);
}
}
}
这是Child 实体的状态管理器:
public partial class ChildStateManager : IStateManager<Child, MyObjContext>
{
public void ChangeState(Child m, MyObjContext ctx)
{
if (m == null) return;
ctx.Children.Attach(m);
if (m.IsDeleted)
{
ctx.ObjectStateManager.ChangeObjectState(m, System.Data.EntityState.Deleted);
}
else
{
if (m.IsNew)
{
ctx.ObjectStateManager.ChangeObjectState(m, System.Data.EntityState.Added);
}
else
{
if (m.IsDirty)
{
ctx.ObjectStateManager.ChangeObjectState(m, System.Data.EntityState.Modified);
}
}
}
SetRelationsState(m, ctx);
}
private void SetRelationsState(Child m, MyObjContext ctx)
{
}
}
IStateManager 是一个简单的接口,只有ChangeState 方法。
如果Child 实体有一个GrandChild 集合,则ChildStateManager.SetRelationsState() 方法将调用GrandChildStateManager.ChangeState() 等等。这有点复杂,但它对我有用,我使用 T4 模板生成状态管理器代码。