Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think the issue is because you are setting the EntityState to Unchanged. The exception you are seeing only happens if the entity keys always exist AND the entity state is not Added. </p> <p>See <a href="http://msdn.microsoft.com/en-us/library/bb896271.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb896271.aspx</a></p> <p>The last paragraph of Considerations for Attaching Objects is: "An InvalidOperationException occurs when an object being attached has the same EntityKey as a different object already present in the object context. This error does not occur if an object in the context with same key but is in the Added state."</p> <p>So the question is, why are you forcing the state to Unchanged instead of leaving it as added?</p> <p>EDIT: Edited after looking at your post again and your comment. Ultimately the problem is you are telling EF "Hey, add these Currency and Country objects with this Customer" but two of those objects already exist. </p> <p>You can use the Attach instead of Add method, but the customer doesn't exist yet. </p> <p>I suggest wrapping these calls in a transactionscope, calling SaveChanges right after creating the Customer, than using Attach rather then Add. If you get errors, you can roll back the transaction if necessary. I don't have a code sample handy, but does what I am saying make sense?</p> <p>Something like:</p> <pre><code> using (TransactionScope scope = new TransactionScope()) { // Now add a new customer Customer customer = new Customer(); customer.Name = "Customer1"; context1.SaveChange(); // Assign a country to the customer // Create a new context (to simulate making service calls over WCF) MyContext context2 = new MyContext(ConnectionString); var countries = from c in context2.Country.Include(c =&gt; c.Currency) where c.Name == "UK" select c; customer.Country = countries.First(); // Assign a currency to the customer // Again create a new context (to simulate making service calls over WCF) MyContext context3 = new MyContext(ConnectionString); customer.Currency = context3.Currency.First(e =&gt; e.Symbol == "GBP"); // Again create a new context (to simulate making service calls over WCF) MyContext context4 = new MyContext(ConnectionString); context4.Customers.Attach(customer); // The following line will result in this exception: // AcceptChanges cannot continue because the object's key values conflict with another // object in the ObjectStateManager. Make sure that the key values are unique before // calling AcceptChanges. context4.SaveChanges(); scope.Complete(); } </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