Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I 've had the same problem with EF. Here's what I ended up doing:</p> <ol> <li>Instead of doing <code>story1.Tags.Add(new Tag { Name = ".net", })</code> yourself, routed all <code>Tag</code> creation through a helper method like this: <code>story1.Tags.Add(GetTag(".net"))</code>.</li> <li>The <code>GetTag</code> method checks the tags in the context to see if it should return an existing entity, like you do. If it does, it returns that.</li> <li>If there is no existing entity, it checks the <code>ObjectStateManager</code> to see if there are <code>Tag</code> entities added to the context but not already written to the db. If it finds a matching <code>Tag</code>, it returns that.</li> <li>If it still has not found the <code>Tag</code>, it creates a new <code>Tag</code>, adds it to the context, and then returns it.</li> </ol> <p>In essence this will make sure that no more than one instance of any <code>Tag</code> (be it already existing or just created) will be used throughout your program.</p> <p>Some example code lifted from my project (uses <code>InventoryItem</code> instead of <code>Tag</code>, but you get the idea).</p> <p>The check in step 3 is done like this:</p> <pre><code>// Second choice: maybe it's not in the database yet, but it's awaiting insertion? inventoryItem = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added) .Where(ose =&gt; ose.EntitySet == context.InventoryItems.EntitySet) .Select(ose =&gt; ose.Entity) .Cast&lt;InventoryItem&gt;() .Where(equalityPredicate.Compile()) .SingleOrDefault(); if (inventoryItem != null) { return inventoryItem; } </code></pre> <p>If the <code>Tag</code> is not found in step 3, here's the code for step 4:</p> <pre><code>inventoryItem = new InventoryItem(); context.InventoryItems.AddObject(inventoryItem); return inventoryItem; </code></pre> <p><strong>Update:</strong></p> <p>It should be used like this:</p> <pre><code>Story story1 = new Story(); story1.Title = "Introducing the Entity Framework"; story1.Tags.Add(GetTag(".net", category, db)); story1.Tags.Add(GetTag("database", category, db)); </code></pre>
 

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