在 ASP MVC Web 应用程序中充分利用实体框架
如何在 ASP MVC3 Web 应用程序中充分利用实体框架(v4.0 或更高版本)?我的主要问题是由于网络的请求响应性质,似乎我必须手动跟踪数据库表单上显示的对象才能执行 CUD 操作。例如。如 编辑和更新 ASP 中的实体框架实体中的建议。 NET MVC 这看起来非常手动。有没有办法让我的会话中的上下文保持某种程度,以便 EF 为我完成所有工作?
How do I get the most out of my Entity Framework (v4.0 or better) in my ASP MVC3 web application? My main problem is due to the request-response nature of the web, it seems I have to manually track objects being displayed on a form to the DB in order to do CUD operations. Eg. as suggested in Editing and Updating Entity Framework entity in ASP .NET MVC this seems awfully manual. Is there a way to keep my context in my session some how such that EF is doing all the work for me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要在会话中存储
ObjectContext
。对每个请求处理使用新的上下文。在这里您可以阅读有关长期生存环境的内容。如果您使用会话中存储的长期存在的上下文,那么加载新数据将会遇到很大的问题。此外,如果您的用户在多个浏览器选项卡(=同一会话)中打开您的应用程序,您可能会得到一些非常意外的结果。如果您只想更新标量值(不更改导航属性),您可以使用:
插入场景:
使用完全分离的对象更新场景:
首先从数据库加载对象更新场景:
删除场景:
可以在不加载的情况下删除实体首先,但如果实体有任何关系,就会引起很多麻烦。
如果您还想修改关系,则可能需要使用
UpdateMode
/TryUpdateModel
,如所讨论的此处或按照描述手动跟踪更改此处。 外键关联上的简单关系更新(即使您不使用代码优先,描述也是相同的)仍然可以通过前面的示例进行处理。Don't store
ObjectContext
in session. Use a new context for each request processing. Here you can read something about long living contexts. If you use long living context stored in session you will have a big problem to load fresh data. Also if your user opens your application in multiple browser tabs (= same session) you can get some very unexpected results.If you want to update just scalar values (no changes in navigation properites) you can use:
Insert scenario:
Update scenario with fully detached object:
Update scenario with loading object first from DB:
Delete scenario:
It is possible to delete the entity without loading it first but if the entity has any relation it couses a lot of troubles.
If you want to modify relations as well it can involve using either
UpdateMode
/TryUpdateModel
as discussed here or tracking changes manually as described here. Simple relation updates on Foreign key association (the description is the same even if you don't use code-first) can be still handled by previous examples.