使用 MVC3 更新 EntityFramework 4 子列表
我正在尝试更新子集合(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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是分离的场景。如果您想保存实体和关系中的更改,您必须说明 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.