问题
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