在静态构造函数中的Database.SetInitializer()? [英] Database.SetInitializer() in a static constructor?

查看:142
本文介绍了在静态构造函数中的Database.SetInitializer()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多人也许知道为什么我们需要使用下面显示的代码。但是,我想将此逻辑分为几层,并且不想在Web层中引用Entity Framework DLL,因此最终将这段代码放在 DbContext 类。

Many are perhaps aware of why we need to use the code shown below. However, I want to separate this logic into layers and I don't want to reference the Entity Framework DLL in my web layer, thus I ended up putting this code in a static constructor of my DbContext class.

这是个坏主意吗?这样做会不会对应用造成性能影响?

Is this a bad idea? Will there be a performance hit on the app by doing this?

Database.SetInitializer<DataContext<T>>(null);


推荐答案

没有值得一提的性能问题。当您创建第一个类实例时,将为您的应用程序调用一次静态构造函数。我在大多数应用程序中都在执行此操作,但尚未注意到任何问题。

There is no performance hit that is worth to be mentioned. A static constructor is called once for your application and when the first class instance is created. I'm doing this in most applications and haven't noticed any problem yet.

您也可以通过数据层的静态方法调用此行而无需引用

You could also call this line through a static method of your data layer without having a reference to EF in the calling web layer assembly.

我相信此行仅设置对初始化程序的内部引用,不会做任何昂贵的事情。当使用第一个上下文实例时,完成了昂贵的工作-发现和建立EF模型。

I believe that this line only sets an internal reference to the initializer and doesn't do anything expensive. The expensive work - discovering and building the EF model - is done when the first context instance is used.

作为补充:在开始时要进行这项昂贵的工作有时可能需要该应用程序,以便在应用程序的最开始具有延迟,并在用户在应用程序中运行第一个查询时避免延迟。要强制初始化,您不仅要设置初始化器,还要运行初始化本身,例如:

As a side note: To have this expensive work at the start of the application might be sometimes desirable in order to have the delay at the very beginning of the application and avoid it when a user is running the first query in the application. To force the initialization you would not only set the intializer but also run the initialization itself, for example like so:

Database.SetInitializer<DataContext>(null);
using (var context = new DataContext())
{
    context.Database.Initialize(false);
}

这篇关于在静态构造函数中的Database.SetInitializer()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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