How To Update EF 4 Entity In ASP.NET MVC 3?

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. ie 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?


I would retrieve the user from the database and update that entity. EF can't just magically know which values are supposed to be modified and which aren't.

If you're concerned about concurrency issues you would need to store the timestamp in the view - usually as a hidden form value.


OK, after some trial and error, I look to have found a solution. Here is my updated Update method in the UserRepository :

public void Update(User user)
{
    using (this.Context)
    {
        var tempUser = new User { usr_id = user.usr_id };

        this.Context.Users.Attach(tempUser);
        this.Context.ApplyCurrentValues("Users", user);
        this.Context.SaveChanges();
    }
}

Some of other examples I tried were very close to the above, but just missed the mark.


请看下面的问题我的Update方法:用EF Code First和ASP.NET MVC部分更新对象即使我不喜欢,我也必须指定字段名称,这很好。

链接地址: http://www.djcxy.com/p/4338.html

上一篇: BackupAgent:“无法恢复软件包...”

下一篇: 如何更新在ASP.NET MVC 3中的EF 4实体?