如何更新EF 4实体在ASP.NET MVC 3? [英] How To Update EF 4 Entity In ASP.NET MVC 3?

查看:75
本文介绍了如何更新EF 4实体在ASP.NET MVC 3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个项目 - 包含一个EDM实体框架模型和一个单独的ASP.NET MVC项目一个类库

I have 2 projects - a class library containing an EDM Entity Framework model and a seperate ASP.NET MVC project.

我在与你想如何编辑和更改保存到使用MVC的实体问题。在我的控制器我有:

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);
        }
    }

我的 UserRepository 有一个更新的方法是这样的:

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();
     }
}

现在,当我点击保存的编辑用户页面上,参数用户只包含填充两个值:id和名字。我认为,是由于这样的事实,我只在视图中显示这两个属性。

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.

我的问题是这样的,如果我更新用户的名字,然后要保存它,什么是我该做一下其他用户这是性质在视图上没有显示,因为它们现在包含在 0的用户或NULL值对象?

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?

我已经读了很多关于使用存根实体,但我越来越无处快,在中没有一个人,我真正看到工作的例子。即我不断收到的EntityKey有关的异常。

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.

有人能指出我如何使用存储库类,通过MVC前端调用以更新EF 4个实体好的教程/例子?

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?

推荐答案

确定,一些试验和错误之后,我一下就找到了解决办法。这里是我的更新更新方法 UserRepository

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.

这篇关于如何更新EF 4实体在ASP.NET MVC 3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆