Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think the problem may be that you are using the instance provided by the model binder as the input to your controller method, so EF does not know anything about that entity and its original state. Your code may look like this:</p> <pre><code>public Review Update(Review review) { _db.Entry(review).State = EntityState.Modified; _db.SaveChanges(); return review; } </code></pre> <p>In that case, EF knows nothing about the <code>Review</code> instance that is being saved. It is trusting you and setting it as modified, so it will save all of its properties to the database, but it does not know the original state\values of that entity.</p> <p>Check the section named <strong>Entity States and the Attach and SaveChanges Methods</strong> of <a href="http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application" rel="nofollow">this tutorial</a>. You can also check the first part of <a href="http://www.prince-kamalanathan.com/tracking-modified-properties-entity-framework/" rel="nofollow">this article</a>, that shows how EF does not know about the original values and will update all properties in the database.</p> <p>As EF will need to know about the original properties, you may first load your entity from the database and then update its properties with the values received in the controller. Something like this:</p> <pre><code>public Review Update(Review review) { var reviewToSave = _db.Reviews.SingleOrDefault(r =&gt; r.Id == review.Id); //Copy properties from entity received in controller to entity retrieved from the database reviewToSave.Property1 = review.Property1; reviewToSave.Property2 = review.Property2; ... _db.SaveChanges(); return review; } </code></pre> <p>This has the advantage that only modified properties will be send and updated in the database and that your views and view models don't need to expose every field in your business objects, only those that can be updated by the users. (Opening the door for having different classes for viewModels and models\business objects). The obvious disadvantage is that you will incur an additional hit to the database.</p> <p>Another option mentioned in the tutorial I referenced above is for you to save the original values somehow (hidden fields, session, etc) and on save use the original values to attach the entity to the database context as unmodified. Then update that entity with the edited fields. However I would not recommend this approach unless you really need to avoid that additional database hit.</p> <p>Hope that helps!</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