Modify and/or delete records under one transaction
<p>I know there are many questions about the error I'm getting, but none of them in the same scenario. I need to update and/or remove several items of an object under one "transaction" with Entity Framework.</p>

<p>I have a list of item objects, let's call it <code>List&lt;ItemObject&gt;</code> and the object which can have those items - call it <code>SuperObject</code>. <strong>ItemObjects</strong> have a complex primary key composed of a <strong>SuperObject</strong>'s primary key and a serial number in that list.</p>

<p><em>Scenario</em>: A user modifies some items and marks others for deletion. Then he clicks a button to save all changes. For my assignment, I need to simulate a transaction - not a good way to use EF, I know. So, I need to set States on the items and then call <code>ctx.SaveChanges()</code>. My problem is that, while updating the serial numbers, I get multiple matching primary key values (I guess), which raises the oh-so-notorious error:</p>

<blockquote>
  <p>Attaching an entity of type 'ItemObject' failed because another entity
  of the same type already has the same primary key value...</p>
</blockquote>

<p>It crashes on a call to <code>ctx.Entry(i).State = EntityState.Modified;</code></p>

<p>Any thoughts on how to solve this? Code given below.</p>

<pre><code>SuperObject objWithItems = (SuperObject)Session["Super"];
List&lt;ItemObject&gt; itemsToKeep = new List&lt;ItemObject&gt;();

foreach(ItemObject io in objWithItems.Items)
                {
                    if (io.Deletion)
                    {
                        ctx.Entry(io).State = EntityState.Deleted;
                    }
                     else
                        itemsToKeep.Add(io);  
                }

                int serial = 0;

                foreach(ItemObject i in itemsToKeep)
                {
                    i.Serial = ++serial;
                    ctx.Entry(i).State = EntityState.Modified;
                }

                ctx.SaveChanges();
            } 

                return RedirectToAction("Read", new { update = false });
        }
</code></pre>

<p>I'm pretty vanilla at this and am still getting to grips with the concepts of EF, so I can't figure out a way go around this error and still meet the demands of the assignment.</p>