EntityFramework.net 4 Updating an Object Using a Simple Method

I looked at this SO question: ADO.net Entity Framework: Update only certian properties for a single object . It helped me a lot. Now I know that I need to bind an entity before making changes to it. But how can I do this:

I have an MVC website, a client update page with fields: identifier, name, address, etc. My MVC parses this on a client object. How to do the following:

  • Refresh my entity and save the changes.
  • Catch an exception if my changes have been made since loading my object.
+4
asp.net-mvc entity-framework
source share
1 answer

Try something like this (pseudo code, I might forget the names of some methods):

public void Update(Customer entity) { using (MyContext ctx = new MyContext()) { // Create a stub entity and attach it Customer db = new Customer {ID = entity.ID}; ctx.Customers.Attach(db); // ctx.AttachTo("Customers", db) in 3.5 sp1 // ApplyPropertyChanges in 3.5 Sp1 ctx.ApplyCurrentValues(entity); ctx.SaveChanges(); } ... } 

This code uses the Stub Entity trick. You can, if you have a relationship, you need to tell EF more about the source object, check out the blog post above because you can do this with stubs too.

Alternatively, if you don't care about concurrency at all, you can simply do this:

 public void Update(Customer entity) { using (MyContext ctx = new MyContext()) { // pull the entity from the database Customer db = ctx.Customers.First(c => c.ID == entity.ID); // ApplyPropertyChanges in 3.5 Sp1 ctx.ApplyCurrentValues(entity); ctx.SaveChanges(); } } 

Hope this helps

Alex james

Entity Framework Tips

+3
source share

All Articles