Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code-first, setting database collation

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
like image 849
Smoller Avatar asked Sep 17 '25 04:09

Smoller


2 Answers

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);
        }
    }
like image 144
huer12 Avatar answered Sep 19 '25 13:09

huer12


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);
         }
     } 
}
like image 22
Ahmed Bahtity Avatar answered Sep 19 '25 15:09

Ahmed Bahtity