Database.SetInitializer() in a static constructor?

2019-07-03 16:03发布

问题:

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