2

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.

Pinte Dani
  • 1,989
  • 3
  • 28
  • 35
  • 1
    That means that tests use different models, why is that? – Gert Arnold Jul 27 '17 at 14:29
  • No, the tests are using the same model. What I want is to disable caching of Dbcontext between unit tests. – Pinte Dani Jul 27 '17 at 19:42
  • Possible duplicate of [How to disable model caching in Entity Framework 6 (Code First approach)](https://stackoverflow.com/questions/29708128/how-to-disable-model-caching-in-entity-framework-6-code-first-approach) – Pinte Dani Jul 28 '17 at 06:23
  • I don't understand. Tests are not affected by a *model* that was loaded before because tests (and any application for that matter) only utilize the model and never modify it. Maybe you mean that you want each test to be unaffected by *data* that were loaded by previous test? – Gert Arnold Jul 28 '17 at 07:15
  • You found anyway to do this? – Sin Jan 21 '19 at 05:44

1 Answers1

0

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.

Sin
  • 1,836
  • 2
  • 17
  • 24