Entity Framework 4.1 “Code First” SetInitializer not being called again after Database.Delete

后端 未结 3 1664
甜味超标
甜味超标 2021-01-12 22:18

Trying to do some unit testing with EF 4.1 code first. I have my live db (SQL Server) and my unit test DB( Sql CE). After fighting (and losing) with EF, Sql CE 4.0 and Trans

相关标签:
3条回答
  • 2021-01-12 22:34

    I got around this by calling 'InitializeDatabase' manually. Like so:

       [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 it may be a bug with EF 4.1 RC.

    0 讨论(0)
  • 2021-01-12 22:46

    It took me almost a day to find out what caused my strange unittest behaviour: the database connection stayed open or the database was not created with a every new test. I searched everywhere for the root of the cause: MSTest (no Admin rights or where working copies of files somehow deleted?), SQL Server Express/CE (login failure?), Unity (objects not disposed?) or Entity Framework (no proper database initialization?). It turned out to be EF. Thanks a lot for the answer!

    0 讨论(0)
  • 2021-01-12 22:47

    It's not a bug, the initializer set with

    System.Data.Entity.Database.SetInitializer
    

    is only called when the context is created for the first time in the AppDomain. Hence, since you're running all your tests in a single AppDomain, it's only called when the first test is ran.

    0 讨论(0)
提交回复
热议问题