什么是创造EF的DbContext实例ASP.NET MVC的最佳方式 [英] What is the best way to create EF DbContext instance for ASP.NET MVC

查看:466
本文介绍了什么是创造EF的DbContext实例ASP.NET MVC的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了支持EF懒加载功能,什么是实例化的最佳途径的DbContext

In order to support lazy loading feature in EF, what is the best way to instantiate DbContext?

我知道的HttpContext 目前的产品创造了良好的地方的DbContext 通过的Application_BeginRequest 方法和 Application_EndRequest 方法,但在一些样品$ C $ MSDN和官方asp.net mvc的网站的CS,他们只是创建的DbContext 在控制器的构造函数,并在控制器的的Dispose()方法处理它。

I know HttpContext's current item is good place to create DbContext via Application_BeginRequest method and Application_EndRequest method, but in some sample codes of MSDN and official asp.net mvc site, they just create DbContext in Controller's constructor and dispose it in controller's Dispose() method.

我觉得这两种方法都不太一样,因为所有这些都要求每模式实现会话。

I think the both ways are not too different because all of those all implement session per request pattern.

我只是想确保我的理解是否正确。

I just want to make sure that my understanding is correct or not.

推荐答案

任何延迟加载这里有可能成为未来的问题陷阱。如果没有DI,没有一个库 - 它很难看到什么工作没有它的延迟加载一个黑客。还你,你打算通过你的实体您的看法。如果是的话这将创建一个坏的重叠。控制器应打包的数据视图,而不是有事情在您的视图后评估。

Any lazy loading here could potentially be a trap for a future issue. Without DI, without a repository - its hard to see anything working without it being a hack for lazy loading. Also do you you plan on passing your entities to your view. If so this is going to create a bad overlap. The controller should package data for your view, not have things evaluated later in your view.

有关MVC的最佳实践,你应该扁平化您的域模型尽可能到视图模型(如扁平化是有道理的),并使用视图模型。既然你最好再知道什么偷懒装,它可能会更有意义,采取打了前面,在查询中渴望负荷使用.INCLUDE(),否则,你可以发出许多许多数据库查询。

For MVC best practices, you should flatten out your domain model as much as possible into a viewmodel (if flattening makes sense) and use the view model. Since you would ideally then know what would be lazy loaded, it may make more sense to take the hit up front and use .Include() in your query to eager load, otherwise you can issue many many queries to the database.

这篇关于什么是创造EF的DbContext实例ASP.NET MVC的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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