简体   繁体   English

处理实体框架上下文

[英]Handling Entity-Framework Context

In the new MVC-5 template there's a file at the App_Start folder called Startup.Auth.cs which contains this lines (along with some other data): 在新的MVC-5模板中, App_Start文件夹中有一个名为Startup.Auth.cs的文件,其中包含以下几行(以及其他一些数据):

// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

What does a single instance per request meen? a single instance per request意味着什么? and what is the difference between calling the ApplicationDbContext like this: 像这样调用ApplicationDbContext什么区别:

var context = HttpContext.GetOwinContext().Get<ApplicationDbContext>();

and placing this declaration as a field in the Controller class : 并将此声明放置为Controller class的字段:

public class HomeController : Controller
{
    private ApplicationDbContext context = new ApplicationDbContext();

Is there a preferred approach for handling the context ? 是否有处理context的首选方法? is a singleton class providing the context preffered? 是提供contextsingleton class吗?

It's just a convenient way of having a context object created whenever one of your action methods are called. 这只是在调用任何一种操作方法时创建上下文对象的便捷方法。 You want a single instance per request because you want all of your objects to be attached to the same context instance. 您希望每个请求一个实例,因为您希望所有对象都附加到同一上下文实例。 You also want the lifetime of your context to be the request lifetime. 您还希望上下文的生命周期为请求生命周期。

If you were to use the second approach private ApplicationDbContext context = new ApplicationDbContext(); 如果要使用第二种方法,则private ApplicationDbContext context = new ApplicationDbContext(); you would have to put that into every controller. 您必须将其放入每个控制器中。 You could create some sort of base controller that does the same thing and just inherit from your base controller. 您可以创建某种功能相同的基本控制器,并且仅从您的基本控制器继承。

Again it's just a convenience method used for demonstration. 同样,这只是用于演示的一种便捷方法。

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

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