Code-first, setting database collation

[亡魂溺海] 提交于 2019-12-24 04:51:33

问题


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

回答1:


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);
        }
    }



回答2:


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);
         }
     } 
}


来源:https://stackoverflow.com/questions/25401290/code-first-setting-database-collation

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