Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework 5 Updating a Record
    primarykey
    data
    text
    <p>I have been exploring different methods of editing/updating a record within Entity Framework 5 in an ASP.NET MVC3 environment, but so far none of them tick all of the boxes I need. I'll explain why.</p> <p>I have found three methods to which I'll mention the pros and cons:</p> <p><strong>Method 1 - Load original record, update each property</strong></p> <pre><code>var original = db.Users.Find(updatedUser.UserId); if (original != null) { original.BusinessEntityId = updatedUser.BusinessEntityId; original.Email = updatedUser.Email; original.EmployeeId = updatedUser.EmployeeId; original.Forename = updatedUser.Forename; original.Surname = updatedUser.Surname; original.Telephone = updatedUser.Telephone; original.Title = updatedUser.Title; original.Fax = updatedUser.Fax; original.ASPNetUserId = updatedUser.ASPNetUserId; db.SaveChanges(); } </code></pre> <p><em>Pros</em></p> <ul> <li>Can specify which properties change</li> <li>Views don't need to contain every property</li> </ul> <p><em>Cons</em></p> <ul> <li>2 x queries on database to load original then update it</li> </ul> <p><strong>Method 2 - Load original record, set changed values</strong></p> <pre><code>var original = db.Users.Find(updatedUser.UserId); if (original != null) { db.Entry(original).CurrentValues.SetValues(updatedUser); db.SaveChanges(); } </code></pre> <p><em>Pros</em></p> <ul> <li>Only modified properties are sent to database</li> </ul> <p><em>Cons</em></p> <ul> <li>Views need to contain every property</li> <li>2 x queries on database to load original then update it</li> </ul> <p><strong>Method 3 - Attach updated record and set state to EntityState.Modified</strong></p> <pre><code>db.Users.Attach(updatedUser); db.Entry(updatedUser).State = EntityState.Modified; db.SaveChanges(); </code></pre> <p><em>Pros</em></p> <ul> <li>1 x query on database to update</li> </ul> <p><em>Cons</em></p> <ul> <li>Can't specify which properties change</li> <li>Views must contain every property</li> </ul> <p><strong>Question</strong></p> <p>My question to you guys; is there a clean way that I can achieve this set of goals?</p> <ul> <li>Can specify which properties change</li> <li>Views don't need to contain every property (such as password!)</li> <li>1 x query on database to update</li> </ul> <p>I understand this is quite a minor thing to point out but I may be missing a simple solution to this. If not method one will prevail ;-)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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