65.9K
CodeProject is changing. Read more.
Home

Extension Method to help with EF Code First updating

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Nov 1, 2011

CPOL
viewsIcon

10032

As far as I know, the "UpdateModel" method is designed to do this. Something like this should work, but I haven't tested it:public ActionResult Edit(Entity entity){ var entityInDbSet = _context.Set.SingleOrDefault(x => x.Id == entity.Id); UpdateModel(entityInDbSet); ...

As far as I know, the "UpdateModel" method is designed to do this. Something like this should work, but I haven't tested it:

public ActionResult Edit(Entity entity)
{
    var entityInDbSet = _context.Set.SingleOrDefault(x => x.Id == entity.Id);
    UpdateModel(entityInDbSet);
    _context.SaveChanges();
}

There's also an overload that lets you specify a list of the properties to update. This is recommended for security reasons, so users can't update properties they shouldn't be allowed to update. See http://msdn.microsoft.com/en-us/library/dd492193.aspx[^] for more information. :)