Dennis Larsen
Dennis Larsen

Reputation:

EntityFramework .net 4 Update entity with a simple method

I was looking at this SO question: ADO.net Entity Framework: Update only certian properties on a detached entity. This was a big help for me. I know now that I need to attach an entity before making my changes to it. But how can do I do this:

I have an MVC website, a Customer Update Page with fields: ID, Name, Address, etc. My MVC is parsing this into a Customer entity. How do I do the following:

Upvotes: 4

Views: 5369

Answers (1)

Alex James
Alex James

Reputation: 20914

Try something like this (pseudo code, I might have misremembered some method names):

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 may if you have relationships need to tell EF more about the original entity, check out the blog post above for more because you can do that using stubs too.

Alternatively if you don't care at all about concurrency you could just 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

Upvotes: 3

Related Questions