Monday, December 3, 2012

Ever wonder how to update a record with Entity Framework?

Well, I'm about to show you how to do that with the controller:

[HttpPost]
public ActionResult Manage( Home data, decimal Id1, decimal Id2 ){
  data.MemberId.Id = Id1;
  data.MemberDetails.Id = Id2;
 
  Identity record = db.Identity.FirstOrDefault( m => m.Id == Id1 );
  record.Copy( data.MemberId );
  Details det = db.Details.FirstOrDefault( m => m.Id == Id2 );
  det.Copy( data.MemberDetails );
  ( (EFDbContext) db ).SaveChanges();

  data.Status =
"Changes were sucessfully saved";
  return View( data );}

What we are accomplishing here is this:

The user has modified his/her Identity and/or Details records and we need to store them in the database.

These records come back to us in a Home record that is simply a holder of several types needed by the home page of the site.

The first thing we do is assign the record numbers to the two records because they are 0 when we get them in the controller.

The next thing we do is read those records from the database again (that connection to the database was lost someplace between the [HttpGet] method that passes a Home record to the View).

Then we call a copy method on the record to copy the updated info into the current record.

We do those last two steps twice once for each record type.

The next thing we do is call .SaveChanges() to write the updated info to the database.

The next thing we do is provide a little feedback to the user in a [NotMapped] field on the Home class.

Finally we return to the View passing the data we recieved.

This is much easier than calling .SqlQuery( "Update..." ); especailly when the detail record has way too many members!


No comments:

Post a Comment