我想在 Entity Framework Code First 创建数据库时设置数据库的默认排序规则。
我尝试过以下方法:
public class TestInitializer<T> : DropCreateDatabaseAlways<T> where T: DbContext
{
protected override void Seed(T context)
{
context.Database.ExecuteSqlCommand("ALTER DATABASE [Test] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
context.Database.ExecuteSqlCommand("ALTER DATABASE [Test] COLLATE Latin1_General_CI_AS");
context.Database.ExecuteSqlCommand("ALTER DATABASE [Test] SET MULTI_USER");
}
}
当 SQL Server 运行时,这似乎运行正常already设置为相同的默认排序规则 Latin1_General_CI_AS。
但是如果我指定一个不同的排序规则,比如 SQL_Latin1_General_CP1_CI_AS 这失败并出现错误,
System.Data.SqlClient.SqlException: Resetting the connection results in a different
state than the initial login. The login fails.
谁能告诉我如何设置排序规则?
使用命令拦截器的解决方案
这绝对是可能的,尽管这有点麻烦。您可以使用命令拦截器更改 CREATE DATABASE 命令。 Il 将拦截发送到数据库的所有命令,根据正则表达式识别数据库创建命令,并使用您的排序规则更改命令文本。
创建数据库之前
DbInterception.Add(new CreateDatabaseCollationInterceptor("SQL_Romanian_Cp1250_CI_AS_KI_WI"));
拦截器
public class CreateDatabaseCollationInterceptor : IDbCommandInterceptor
{
private readonly string _collation;
public CreateDatabaseCollationInterceptor(string collation)
{
_collation = collation;
}
public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext) { }
public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
// Works for SQL Server
if (Regex.IsMatch(command.CommandText, @"^create database \[.*]$"))
{
command.CommandText += " COLLATE " + _collation;
}
}
public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) { }
public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) { }
public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext) { }
public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext) { }
}
Remarks
由于数据库从一开始就使用正确的排序规则创建,因此所有列都将自动继承该排序规则,并且之后您不必更改它们。
请注意,它将影响应用程序域内发生的任何后续数据库创建。因此,您可能希望在创建数据库后删除拦截器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)