Database.SetInitializer() in a static constructor?

戏子无情 提交于 2019-12-23 22:01:44

问题


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);

回答1:


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.

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);
}


来源:https://stackoverflow.com/questions/16490087/database-setinitializer-in-a-static-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!