Monthly Archives: May 2011

Update a record through the Entity Framework using Attach

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;



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));