Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Extension Method to help with EF Code First updating

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
1 Nov 2011CPOL 9.6K   2
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:


C#
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. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Facebook
United States United States
I'm a web developer specialising in ASP.NET MVC, PHP and JavaScript. I've got several years of web development experience and am always trying new technologies.

Comments and Discussions

 
GeneralReason for my vote of 5 Great stuff, I wasn't aware of the U... Pin
George Danila1-Nov-11 5:13
George Danila1-Nov-11 5:13 
GeneralRe: Glad it helped, I only discovered it while reading through t... Pin
Daniel Lo Nigro1-Nov-11 12:33
Daniel Lo Nigro1-Nov-11 12:33 
Glad it helped, I only discovered it while reading through tutorials. Smile | :)

Your code would still be very helpful if you wanted to do this outside of a controller (as UpdateModel is a controller method, it can't really be used elsewhere).

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.