如何在 ASP.NET MVC 3 中更新 EF 4 实体?

发布于 2024-10-12 05:28:01 字数 1240 浏览 3 评论 0原文

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

我对如何使用 MVC 编辑和保存对实体的更改感到有疑问。在我的控制器中,我有:

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 有一个像这样的 Update 方法:

public void Update(User user)
{
     using (var context = new PDS_FMPEntities())
     {
         context.Users.Attach(testUser);
         context.ObjectStateManager.ChangeObjectState(testUser, EntityState.Modified);
         context.SaveChanges();
     }
}

现在,当我在编辑用户页面上单击“保存”时,参数 user 仅包含两个值填充:Id 和 FirstName。我认为这是因为我只在视图中显示这两个属性。

我的问题是,如果我要更新用户的名字,然后想要保存它,我应该如何处理视图上未显示的其他 User 属性,因为它们现在user 对象中包含 0 或 NULL 值?

我已经阅读了很多有关使用存根实体的内容,但我一无所获,因为我见过的示例都没有真正起作用。即我不断收到 EntityKey 相关的异常。

有人可以向我指出一个关于如何使用由 MVC 前端调用的存储库类更新 EF 4 实体的好教程/示例吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

自找没趣 2024-10-19 05:28:01

我将从数据库中检索用户并更新该实体。 EF 不能神奇地知道哪些值应该修改,哪些不应该修改。

如果您担心并发问题,则需要将时间戳存储在视图中 - 通常作为隐藏的表单值。

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.

a√萤火虫的光℡ 2024-10-19 05:28:01

好吧,经过一番尝试和错误,我看起来找到了解决方案。这是我在 UserRepository 中更新的 Update 方法:

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

我尝试的其他一些示例与上面的非常接近,但只是错过了标记。

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.

风铃鹿 2024-10-19 05:28:01

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

Please look at my Update method on the following question:
Partially updating object with EF Code First and ASP.NET MVC
This works nice, even when I dislike, that I have to specify the field names.

小清晰的声音 2024-10-19 05:28:01

我发现 asp.net 网站上的这个教程非常有帮助: 使用 MVC 开始使用 EF - 更新相关数据

需要注意的方法是 TryUpdateModel它将以“标准”方式更新相关模型(将实体设置为修改状态并传入所有内容),然后让您自定义某些属性的更新方式。

我遇到了实体键的问题,这帮助我解决了这些问题。

I found this tutorial on the asp.net website to be very helpful: Getting Started with EF using MVC - Updating Related Data

The method to pay attention to is TryUpdateModel which will update the related model in the "standard" manner (setting the entity to a modified state and passing everything in) and then will let you customize how certain properties are updated.

I ran into problems with entity keys and this helped me get past those.

泪意 2024-10-19 05:28:01

看看上面的链接,我认为这是一个非常相似的案例(有解决方案)。祝你好运

挽你眉间 2024-10-19 05:28:01

这可能有点晚了来帮助回答这个问题,但也许对其他人有帮助。在我看来,您遇到的主要问题是由于读取实体的数据库上下文实例在页面呈现后被释放而引起的。因此,当您尝试保存它时,这是上下文的一个新实例,因此它不知道先前的上下文调用。因此,实体框架必须更新数据库中的所有行,因为它无法知道哪些行已更改。

话虽这么说,我发现保存所有旧数据并更新我想要更改的内容的最佳方法是首先对数据库进行新调用,设置模型(或其他任何内容)所需的所有信息您用于存储数据)到数据库中当前的内容。然后对该信息进行必要的更改,然后将结果保存到数据库中。

您可以在此处查看有关实现基本 CRUD 的教程以获取更多信息:
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-basic-crud-function性-with-the -asp-net-mvc-应用程序中的实体框架

This is probably a little late to help answer the question, but maybe it will help some one else. It seems to me that the main problem you are having is caused by the fact that the database context instance that reads an entity is disposed after a page is rendered. So when you try to save it, this is a new instance of a context, which therefore has no knowledge of the previous context call. Entity Framework therefore has to update all rows in the database, because it has no way of knowing which rows were changed.

This being said, the best method that I have found for saving all of the old data, and updating what I want to change, is to make a new call to the database first, setting all of the required information for a Model (or whatever you are using to store your data) to what is currently in the DB. Then making the necessary changes to that information, and then saving the result to the DB.

You can look at the tutorial on Implementing Basic CRUD here for more information:
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文