Is there any way to configure what collation to use when EF creates the database?
Or is there some kind of hook to set the collation after the database is created but before the tables are created?
- Entity Framework 6.1.1
- MS SQL 2012
Is there any way to configure what collation to use when EF creates the database?
Or is there some kind of hook to set the collation after the database is created but before the tables are created?
I solved the issue by creating the DB myself. The base class is then creating the tables into the empty DB:
public class MyInitializer : CreateDatabaseIfNotExists<MasterDataModel>
{
public override void InitializeDatabase(MasterDataModel context)
{
if(!context.Database.Exists())
{
using (SqlConnection connection = new SqlConnection("YourConnectionString"))
{
connection.Open();
using(SqlCommand command = new SqlCommand(string.Format("CREATE DATABASE {0} COLLATE Latin1_General_CI_AS", "NameOfDatabase"), connection))
{
command.ExecuteNonQuery();
}
}
SqlConnection.ClearAllPools();
}
base.InitializeDatabase(context);
}
}
The issue could be solved by opening dedicated connection to the database and execute the alter sql command
through it.
Notice how we use the connection string passed from the framework to open the new connection. Thank for @huer12 as I used his code.
public class DBInitializer<T > : CreateDatabaseIfNotExists<T> where T : DbContext
{
void SetDatabaseCollation(DbContext context)
{
using (SqlConnection connection = new SqlConnection(context.Database.Connection.ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(string.Format("ALTER DATABASE [{0}] COLLATE Latin1_General_CI_AS", context.Database.Connection.Database), connection))
{
command.ExecuteNonQuery();
}
SqlConnection.ClearAllPools();
connection.Close();
}
}
protected override void Seed(T context)
{
SetDatabaseCollation(context);
}
}
public class MyDbContext : MyDbContext
{
public MyDbContext() : base("ConnectionString", throwIfV1Schema: false)
{
Database.SetInitializer(new DBInitializer<MyDbContext>());
if(!Database.Exists())
{
Database.Initialize(true);
}
}
}