Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Legen Sie die Datenbanksortierung in Entity Framework Code-First Initializer fest

Lösung mit einem Command Interceptor

Es ist definitiv möglich, obwohl es ein bisschen wie ein Hack ist. Sie können den CREATE DATABASE-Befehl mit einem Command Interceptor ändern. Er fängt alle an die Datenbank gesendeten Befehle ab, erkennt den Datenbankerstellungsbefehl basierend auf einem Regex-Ausdruck und ändert den Befehlstext mit Ihrer Sortierung.

Vor der Datenbankerstellung

DbInterception.Add(new CreateDatabaseCollationInterceptor("SQL_Romanian_Cp1250_CI_AS_KI_WI"));

Der Abfangjäger

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

Bemerkungen

Da die Datenbank von Anfang an mit der richtigen Sortierung erstellt wird, erben alle Spalten automatisch diese Sortierung und Sie müssen sie anschließend nicht ÄNDERN.

Beachten Sie, dass dies Auswirkungen auf alle späteren Datenbankerstellungen innerhalb der Anwendungsdomäne hat. Daher möchten Sie vielleicht den Interceptor entfernen, nachdem die Datenbank erstellt wurde.