Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Not exactly your way, because I'm using POCO with state flags, but it can be applied to generated entities as well. This is a recursive approach to manage the state of the parent entity and children entities. This is the state manager class for the <code>Parent</code> entity:</p> <pre><code>public partial class ParentStateManager : IStateManager&lt;Parent, MyObjContext&gt; { private IStateManager&lt;Child, MyObjContext&gt; _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 =&gt; !p.IsDeleted)) { _ChildStateManager.ChangeState(varChild, ctx); } while (m.Children.Where(p =&gt; p.IsDeleted).Any()) { _ChildStateManager.ChangeState(m.Children.Where(p =&gt; p.IsDeleted).LastOrDefault(), ctx); } } } </code></pre> <p>And this is the state manager for the <code>Child</code> entity:</p> <pre><code>public partial class ChildStateManager : IStateManager&lt;Child, MyObjContext&gt; { 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) { } } </code></pre> <p><code>IStateManager</code> is a simple interface which only has <code>ChangeState</code> method. If the <code>Child</code> entity had a <code>GrandChild</code> collection, the <code>ChildStateManager.SetRelationsState()</code> method would call the <code>GrandChildStateManager.ChangeState()</code> and so on. It's a bit complicated, but it works for me and I generate the state manager code using T4 templates. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload