How To Update EF 4 Entity In ASP.NET MVC 3?
Posted
by
Jason Evans
on Stack Overflow
See other posts from Stack Overflow
or by Jason Evans
Published on 2011-01-12T10:20:19Z
Indexed on
2011/01/12
10:53 UTC
Read the original article
Hit count: 233
Hi there.
I have 2 projects - a class library containing an EDM Entity Framework model and a seperate ASP.NET MVC project.
I'm having problems with how your suppose to edit and save changes to an entity using MVC. In my controller I have:
public class UserController : Controller
{
public ActionResult Edit(int id)
{
var rep = new UserRepository();
var user = rep.GetById(id);
return View(user);
}
[HttpPost]
public ActionResult Edit(User user)
{
var rep = new UserRepository();
rep.Update(user);
return View(user);
}
}
My UserRepository
has an Update method like this:
public void Update(User user)
{
using (var context = new PDS_FMPEntities())
{
context.Users.Attach(testUser);
context.ObjectStateManager.ChangeObjectState(testUser, EntityState.Modified);
context.SaveChanges();
}
}
Now, when I click 'Save' on the edit user page, the parameter user
only contains two values populated: Id, and FirstName. I take it that is due to the fact that I'm only displaying those two properties in the view.
My question is this, if I'm updating the user's firstname, and then want to save it, what am I suppose to do about the other User
properties which were not shown on the view, since they now contain 0 or NULL values in the user
object?
I've been reading a lot about using stub entities, but I'm getting nowhere fast, in that none of the examples I've seen actually work. i.e. I keep getting EntityKey related exceptions.
Can someone point me to a good tutorial/example of how to update EF 4 entities using a repository class, called by an MVC front-end?
Cheers. Jas.
© Stack Overflow or respective owner