Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem is that this query</p> <pre><code>string thisQueryWillMessThingsUp = context.SaleMethods.Where(m =&gt; m.Id == 2).Single().Name; </code></pre> <p>brings one instance of the SaleMethod entity into the context and then this code</p> <pre><code>context.Entry(method).State = System.Data.EntityState.Modified; </code></pre> <p>attaches <em>a different instance</em> to the context. Both instances have the same primary key, so EF thinks that you are trying to attach two different entities with the same key to the context. It doesn't know that they are both supposed to be the same entity.</p> <p>If for some reason you just need to query for the name, but don't want to actually bring the full entity into the context, then you can do this:</p> <pre><code>string thisQueryWillMessThingsUp = context.SaleMethods.Where(m =&gt; m.Id == 2).AsNoTracking().Single().Name; </code></pre> <p>If what you are tying to do is update an existing entity and you have values for all mapped properties of that entity, then the simplest thing to do is to not run the query and just use:</p> <pre><code>context.Entry(method).State = System.Data.EntityState.Modified; </code></pre> <p>If you don't want to update all properties, possibly because you don't have values for all properties, then querying for the entity and setting properties on it before calling SaveChanges is an acceptable approach. There are several ways to do this depending on your exact requirements. One way is to use the Property method, something like so:</p> <pre><code>var salesMethod = context.SaleMethods.Find(2); // Basically equivalent to your query context.Entry(salesMethod).Property(e =&gt; e.Name).CurrentValue = newName; context.Entry(salesMethod).Property(e =&gt; e.SomeOtherProp).CurrentValue = newOtherValue; context.SaveChanges(); </code></pre> <p>These blog posts contain some additional information that might be helpful:</p> <p><a href="http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx">http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx</a></p> <p><a href="http://blogs.msdn.com/b/adonet/archive/2011/01/30/using-dbcontext-in-ef-feature-ctp5-part-5-working-with-property-values.aspx">http://blogs.msdn.com/b/adonet/archive/2011/01/30/using-dbcontext-in-ef-feature-ctp5-part-5-working-with-property-values.aspx</a></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