Entity Framework 4.1 "Code First" SetInitializer is not called again after Database.Delete

First, try to run some unit tests with EF 4.1 code. I have my live db (SQL Server) and my unit test DB (Sql CE). After struggling (and losing) with EF, Sql CE 4.0 and transaction support, I decided that the easiest way to run my test was as follows:

  • Create db
  • Run test
  • Delete Db
  • Rinse and repeat

I have the functions [Setup] and [TearDown]:

[SetUp] public void Init() { System.Data.Entity.Database.SetInitializer(new MyTestContextInitializer()); _dbContext = ContainerFactory.Container.GetInstance<IContext>(); _testConnection = _dbContext.ConnectionString; } [TearDown] public void Cleanup() { _dbContext.Dispose(); System.Data.Entity.Database.Delete(_testConnection); } 

The problem is that System.Data.Entity.Database.SetInitializer does not call MyTestContextInitializer after the first test.

Therefore, the second test fails:

System.Data.EntityException: The underlying provider could not open Open.
----> System.Data.SqlServerCe.SqlCeException: Database file not found. Check database path

TIA for any pointers

+6
nunit entity-framework sql-server-ce-4
source share
3 answers

I circumvented this by manually calling "InitializeDatabase". For instance:

  [SetUp] public void Init() { var initializer = new MyTestContextInitializer(); System.Data.Entity.Database.SetInitializer(initializer); _dbContext = ContainerFactory.Container.GetInstance<IContext>(); initializer.InitializeDatabase((MyTestContext)_dbContext); _testConnection = _dbContext.ConnectionString; } [TearDown] public void Cleanup() { System.Data.Entity.Database.Delete(_testConnection); _dbContext.Dispose(); } 

I think this may be a bug with EF 4.1 RC.

+7
source share

This is not a mistake, initializer with

 System.Data.Entity.Database.SetInitializer 

only called when the context is first created in AppDomain. Therefore, since you use all your tests in one application, it is called only when the test is first run.

+2
source share

It took me almost a day to find out what caused my strange unittest behavior: the database connection remained open or the database was not created with each new test. I searched everywhere for the root cause: MSTest (no administrator privileges or have working copies of files been deleted somewhere?), SQL Server Express / CE (logon failure?), Unity (objects not deleted?) Or Entity Framework (there is no corresponding database initialization? ) It turned out to be EF. Thank you very much for your answer!

+1
source share

All Articles