views:

558

answers:

2

I was looking at this SO question: http://stackoverflow.com/questions/1168215/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:

  • Update my entity and Save the changes to it.
  • Catch the exception if my changes have been made since I loaded my entity.
+1  A: 

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

Alex James
A: 

Hay Alex James

I have selected you method and changed it into my Domain.

public void Update(Section entity)
{

   using (Data.WebsiteEntities ctx = new Data.WebsiteEntities())
   { 
      Section db = new Section {SectionGuid = entity.SectionGuid};
      ctx.Sections.Attach(db);

      ctx.ApplyCurrentValues(entity); // GET and error here because the method does not exists.  
      ctx.SaveChanges();
   }
}

The only method that I have with the same name is: TEntity ApplyCurrentValues<TEntity>(string entitySetName, TEntity currentEntity)

Description: Sets the System.Data.Objects.ObjectStateEntry.CurrentValues property of the System.Data.Objects.ObjectStateEntry to match the property values of a supplied object.

So does this work?

Dennis Larsen