实体框架和对象上下文寿命在ASP.NET MVC [英] Entity Framework and Object Context lifetime in ASP.NET MVC

查看:176
本文介绍了实体框架和对象上下文寿命在ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架在我的项目,我有,一旦我通过我的实体视图中的问题(请记住,这些实体的线沿线的延迟初始化对象:Products.Owner,其中老板是延迟初始化的对象)我得到一个运行时异常告诉我,ObjectContext的是超出范围。

I'm using Entity Framework in my project, and I have the problem that, once I pass my entities to a View (keep in mind that these entities have lazy-initialized objects along the lines of: Products.Owner, where owner is an object that is lazily initialized) I get a run-time exception telling me that the ObjectContext is out of scope.

现在这是有道理的,因为我正在从服务实体与使用(....实体...){....}语句,这意味着返回结果时,它被设置。

Now this makes sense since I am getting the entities from a Service with a using (.... entities...) { .... } statement, which means it is disposed when the result is returned.

如何我会解决这个问题,并有对象上下文还活着,从开始到结束。谢谢你。

How would I get around this and have an Object Context that is alive from start to end. Thanks.

推荐答案

一个选项是资源库与请求所包含的ObjectContext的Dispose方法处置相关联,并有库实现IDisposable,并拥有,而不是使用比较熟悉的使用模式内部控制器动作。

One option is to associate the repository with the Request, and have the Repository implement IDisposable, and have the Dispose method dispose of the contained ObjectContext, rather than using the more familiar using pattern inside your controller actions.

这篇关于实体框架和对象上下文寿命在ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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