RSS

Update a record through the Entity Framework using Attach

11 May

Performing basic Create, Read, Update and Delete Operations via the Entity Framework is very straight forward.  However take this scenario :

  1. The EF is used to return a Customer Record to the Presentation Layer
  2. A User then modifies the Customer record
  3. The modified record is sent back to the EF to update the record in the database.

To Update the record we can write the following code :

public bool UpdateCustomer(Customer customer){

    Customer cust = entities.Customers.FirstOrDefault(c => c.ID == customer.ID);

    cust.Forname = customer.Forename;

    cust.Surname = customer.Surname;

    entities.SaveChanges();

}

But what if the object we are updating contains a lot of attributes.  Surely updating each attribute seperately before calling a Save is a little overkill.

Luckily we are providied with a solution which allows us to attach to a record within the context, perform a straight replace on the record with the new modified record and save back the changes, and all in just 3 lines of code:

bool UpdateCustomer(Customer customer) {

    entities.Customers.Attach(entities.Customers.Single(c => c.ID == customer.ID));

    entities.Customers.ApplyCurrentValues(customer);

    entities.Savechanges();

}

Advertisements
 

9 responses to “Update a record through the Entity Framework using Attach

  1. Dan

    May 11, 2011 at 1:06 pm

    Very useful tip! thanks 😉

     
  2. sendelany

    December 8, 2011 at 9:52 pm

    Very useful. Saved me lots of time.

     
  3. Jay

    November 3, 2012 at 6:32 am

    Thanks! It helps me a lot.

     
  4. Vinod

    November 8, 2012 at 10:11 am

    Thanks. It help me

     
  5. marcoslimagon

    November 27, 2012 at 11:40 am

    For EF 5 this method was changed to:

    Configuracao original = db.Configuracoes.Find(item.Codigo);

    if (original != null)
    {
    db.Entry(original).CurrentValues.SetValues(item);

    db.SaveChanges();
    }

     
  6. Ron

    January 4, 2013 at 10:29 pm

    Thanks for the update marcoslimagon! And thanks for the original post. This is very helpful

     
  7. Ali

    January 19, 2013 at 8:15 am

    Thank you very much marcoslimagon!

     
  8. Mahmoud

    May 21, 2013 at 8:44 am

    thank you its helpful

     
  9. Balle

    August 24, 2013 at 3:08 pm

    Gr8.. The solution worked for me…thanks!
    I surfed so many websites….but they only confused.
    Thanks ones again!

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: