Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I guess you get the exception only if <code>customer.Currency</code> and <code>customer.Country.Currency</code> refer to the same currency, i.e. have the same identity key. The problem is that those two currency objects come from different object contexts, therefore they are different objects (<code>ReferenceEquals(customer.Currency, customer.Country.Currency)</code> is <code>false</code>). When you attach both to your last context (by setting the <code>State</code>) the exception occurs because they are two different objects with the same key.</p> <p>Looking at your code, perhaps the easiest option would be to check if the currency you want to assign to the customer is the same as the country's currency before you even load the currency, something like:</p> <pre><code>if (customer.Country.Currency.Symbol == "GBP") customer.Currency = customer.Country.Currency; // currencies refer now to same object, avoiding the exception else { MyContext context3 = new MyContext(ConnectionString); customer.Currency = context3.Currency.First(e =&gt; e.Symbol == "GBP"); } </code></pre> <p>(I assume here that <code>Symbol</code> is the key for currency or a least unique in the DB.) You would also avoid one service/DB call if the currencies are the same.</p> <p>Other options would be: Don't include the currency in the country query, if you can. Your solution to set <code>customer.Country.Currency</code> to <code>null</code> (not bad at all). Make the references to the two currencies equal in the last context before you add the customer (<code>if (customer.Country.Currency.Symbol == customer.Currency.Symbol) customer.Currency = customer.Country.Currency;</code>). Reload the currencies in your last context and assign them to the customer.</p> <p>But that's all not really a "nicer way" to solve the problem, only another way - in my opinion.</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