使用 MVC3 更新 EntityFramework 4 子列表

发布于 2024-10-26 20:38:11 字数 561 浏览 1 评论 0 原文

我正在尝试更新子集合(MVC3 和实体框架 4) 我无法获得任何更新来保留。

        [HttpPost]
        public ActionResult Edit(Subject EditedSubject, IEnumerable<SubjectTagPin> SubjectTagPins)
        {
            try
            {
                XDataModelContainer model = new XDataModelContainer();
                model.Subjects.Attach(EditedSubject);
                model.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View(EditedSubject);
            }
        }

I'm trying to update a child collection (MVC3 and Entity Framework 4)
I cant get any updates to get persisted.

        [HttpPost]
        public ActionResult Edit(Subject EditedSubject, IEnumerable<SubjectTagPin> SubjectTagPins)
        {
            try
            {
                XDataModelContainer model = new XDataModelContainer();
                model.Subjects.Attach(EditedSubject);
                model.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View(EditedSubject);
            }
        }

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

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

发布评论

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

评论(1

你对谁都笑 2024-11-02 20:38:11

这是分离的场景。如果您想保存实体和关系中的更改,您必须说明 EF 执行了哪些更改。 EF 不知道这一点,并且它不会与数据库中的状态执行任何自动同步。这个问题也被称为使用分离的对象图,在我看来,这是实体框架(可能是全局 ORM)中最大的复杂性。我回答了类似问题,您还可以找到<此处有一个 href="https://stackoverflow.com/questions/4653834/asp-net-mvc-ef4-poco-repository-how-to-update-relationships">相关问题。

一般答案是您必须知道创建或删除了哪些关系,并且必须手动设置相关对象的状态(在一对一或一对多的情况下)或关系状态(在多对多的情况下) )。如果您有多对多,并且您可以在同一请求中创建与现有对象的关系、创建新的相关对象或删除现有的相关对象,那么复杂性会更糟。

我的一般建议是使用不太优雅但更简单的方法:从数据库加载实体图并将传入的更改合并到附加图中。

This is detached scenario. If you want to save changes in entities and in relations you must say EF what changes were executed. EF doesn't know it and it doesn't perform any automatic synchronization with the state in the database. This problemetic is known also as working with detached object graphs and in my opinion it is the biggest complexity in entity framework (and probably ORM globally). I answered similar question and you can also found related question here.

General answer is you must know which relations were created or removed and you must manually set either state of related object (in case of one-to-one or one-to-many) or state of relation (in case many-to-many). The complexity is even worse if you have many-to-many and you can create relation to existing objects, create new related objects or delete existing related objects in the same request.

My general advice is using less elegant but much easier approach: load your entity graph from the database and merge incomming changes into attached graph.

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