Entity Framework 6 SetInitializer DbContext does not work for SQL Server Express and SQL Server Compact

天涯浪子 提交于 2020-01-04 03:20:12

问题


I've got a problem with creating a new database every time my application starts.

I read this post Entity Framework Database.SetInitializer simply not working , but it didn't help.

Here is my code:

public DatabaseContext(DatabaseType type) : base("name=" + type)
{
   Database.SetInitializer(new DropCreateDatabaseAlways<DatabaseContext>());
}

and I'm calling

Database.Initialize(true);

doesn't matter if true or false, both doesn't work.

Later in my application I also "work" with the database so the initializer should definitely be called.

I open the context via "using". And even if I do a transaction like this:

database.RoleRepository.Insert(new Role());
database.Save();

it doesn't work.

The funny thing is that it works with LocalDB but not with Compact Edition or SQL Server Express. I work with all three databases inside the same application (the project requires this), maybe that's the mistake? LocalDB is called first.

Here are my connections strings:

<connectionStrings>
    <add name="LocalDB" 
         connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Database.DatabaseContext;integrated security=True;MultipleActiveResultSets=True" 
         providerName="System.Data.SqlClient"/>
    <add name="CompactEdition" 
         connectionString="Data Source=CompactEditionDB.sdf" 
         providerName="System.Data.SqlServerCe.4.0"/>
    <add name="SQLExpress" 
         connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SQLExpressDatabase;User Instance=false;MultipleActiveResultSets=true;Integrated Security=SSPI" 
         providerName="System.Data.SQLClient"/>
</connectionStrings>

Do you know why it only works with LocalDB?

EDIT:

Found out that it only works with the first context/database, doesn't matter which type. Both methods

Database.SetInitializer(new DropCreateDatabaseAlways<DatabaseContext>());
Database.Initialize(true);

are called, but it looks like as if they are not executed. As already mentioned they all have the same context but consist of different objects.

Why is only the first database recreated?

来源:https://stackoverflow.com/questions/24889864/entity-framework-6-setinitializer-dbcontext-does-not-work-for-sql-server-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!