Entity Framework DbContext ModelCaching property not available

877 Views Asked by At

I am writing some unit tests for Database creation using EF codefirst. During execution of Unit tests, the DBContext->OnModelCreating method is executed only 1 time, and the model is then cached for the rest of the remaining tests.

I want to be able to execute the "OnModelCreating" for each unit test separately, by trying to set the ModelCaching property, like specified in the Documentation:

// Remarks:
//     Typically, this method is called only once when the first instance of a derived
//     context is created. The model for that context is then cached and is for all
//     further instances of the context in the app domain. This caching can be disabled
//     by setting the ModelCaching property on the given ModelBuidler, but note that
//     this can seriously degrade performance. More control over caching is provided
//     through use of the DbModelBuilder and DbContextFactory classes directly.
protected virtual void OnModelCreating(DbModelBuilder modelBuilder);

However, there is no such Property "ModelCaching" on this modelbuilder.

How else can I disable this model caching? Tests are running fine one by one, but because of this caching they are failing when running in a row.

Better said, how can I force the ApplicationDbContext -> OnModelCreating to be run for each test individually? Now it is run only once, when it is first used for a bunch of Unit tests.

1

There are 1 best solutions below

0
On

Seems like this property is not available anymore. You need to keep different DB models and initialize your context for different connection.

This answer helped me in my case. By implementing the IDbModelCacheKeyProvider EF can cache multiple DB model for you based on the different CacheKey.