Entity Framework 5 easier way to update record

In the past with EF if you wanted to update a record you would need to do something like this:

 public HttpResponseMessage PutCustomer(Customer customer)
        {
            using (var context = new ChinookContext())
            {
                var request = context.Customers.Single(c => c.CustomerId == customer.CustomerId);

                // todo this has to have an easier way.  Customer.Attach throws an error
                request.FirstName = customer.FirstName;
                request.LastName = customer.LastName;
                request.Address = customer.Address;
                request.City = customer.City;
                request.PostalCode = customer.PostalCode;
                request.State = customer.State;
                request.Country = customer.Country;
                request.Fax = customer.Fax;
                request.Email = customer.Email;
                request.Company = customer.Company;

                context.SaveChanges();

                var response = Request.CreateResponse(HttpStatusCode.Accepted, customer);
                response.Headers.Location = new Uri(Request.RequestUri, string.Format("Customer/{0}", customer.CustomerId));
                return response;
            }
        }

As you may notice this can get tedious and rather large as more fields need updating.   In Entity Framework 5  we get a wonderful new method ‘SetValues’.  With this new method we can change the above code from that to this:

 public HttpResponseMessage PutCustomer(Customer customer)
        {
            using (var context = new ChinookContext())
            {
                var original = context.Customers.Find(customer.CustomerId);

                if (original != null)
                {
                    context.Entry(original).CurrentValues.SetValues(customer);
                    context.SaveChanges();
                }

                var response = Request.CreateResponse(HttpStatusCode.Accepted, customer);
                response.Headers.Location = new Uri(Request.RequestUri, string.Format("Customer/{0}", customer.CustomerId));
                return response;
            }
        }
Advertisement
This entry was posted in Entity Framework, Web and tagged , . Bookmark the permalink.

2 Responses to Entity Framework 5 easier way to update record

  1. Maybe you should mention the over/under posting problem that’s becoming even worse with this approach.

  2. Ivan Franjic says:

    I don’t see any benefit from this approach. If you’re not using viewmodels and a mapping library, you just attach the entity and set it to modified. That way you make one db call less.

    But I prefer to use viewmodels and a mapping library, because one of the things I get from that is the ability to control which fields can be updated.

Comments are closed.