简体   繁体   English

带有实体框架的ASP.NET MVC

[英]ASP.NET MVC with Entity Framework

I'm thinking it would be smart to setup the Entity object context in Application_BeginRequest, store it in Request.items, use it throughout the request and dispose it in Application_EndRequest. 我认为在Application_BeginRequest中设置Entity对象上下文,将它存储在Request.items中,在整个请求中使用它并将其部署在Application_EndRequest中是明智的。 That way the context is always available and I can navigate the Entity Framework object graph in my views, lazy loading what I haven't already eager fetched. 这样,上下文始终可用,我可以在我的视图中导航实体框架对象图,延迟加载我尚未急切获取的内容。

I think this would make it like developing on Ruby on Rails . 我认为这会让它像在Ruby on Rails上开发一样。

It might be I should be shot for speaking such heresy, but it's so crazy it just might work :) 可能是因为说出这样的异端邪说我应该被枪杀,但它太疯狂了它可能会起作用:)

I can't get Application_BeginRequest and ..EndRequest to fire on ASP.NET MVC though. 我无法在ASP.NET MVC上启动Application_BeginRequest和..EndRequest。 Aren't they fired? 他们不是被解雇了吗? Any special trick I need to do? 我需要做什么特别的伎俩?

The object context in EF, like the data context in L2S, is designed as a "unit of work", They're not thread-safe, and they're not designed to be long lived. EF中的对象上下文,如L2S中的数据上下文,被设计为“工作单元”,它们不是线程安全的,并且它们的设计并不长久。

In MVC, the best strategy is to create one in the controller's constructor (implicitly or explicitly, doesn't matter) and then dispose it in the Dispose method. 在MVC中,最好的策略是在控制器的构造函数中创建一个(隐式或显式,无关紧要),然后将它配置在Dispose方法中。 Of course, EF doesn't do lazy loading, so you'll have to find your own way to be lazy. 当然,EF不会进行延迟加载,所以你必须找到自己的懒惰方式。 :) :)

The 1.0 build of ASP.NET MVC let me hook up event handlers on both beginrequest and endrequest, newing up a SessionScope and storing it in HttpContext.Items in beginrequest (I switched to Castle ActiveRecord) and in endrequest I pick the sessionscope out from HttpContext.Items and dispose it. ASP.NET MVC的1.0版本允许我在beginrequest和endrequest上连接事件处理程序,新建一个SessionScope并将其存储在beginrequest中的HttpContext.Items中(我切换到Castle ActiveRecord)并在endrequest中从HttpContext中选择sessionscope .Items并处理它。 This enables lazy loading throughout the request lifecycle. 这可以在整个请求生命周期中启用延迟加载。 (can even navigate object graph in views.) (甚至可以在视图中导航对象图。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM