4

我需要在每个数据库会话开始时执行一些 SQL 命令。我通过 DbContext 使用 Entity Framework 5 与 Oracle 11g 数据库对话。

我想执行:

ALTER SESSION SET NLS_COMP=ANSI;
ALTER SESSION SET NLS_SORT=BINARY_CI;

在会话创建开始时进行不区分大小写的搜索。
我该怎么做才能做到最好?

我已将命令放在 dbContext 的构造函数中,但只有简单的单元测试,它似乎确实有效。但不确定这是否是正确的做法

public partial class Entities : DbContext
{
    public Entities()
        : base("name=Entities")
    {
        this.Database.ExecuteSqlCommand("ALTER SESSION SET NLS_COMP=ANSI");
        this.Database.ExecuteSqlCommand("ALTER SESSION SET NLS_SORT=BINARY_CI");
    }
}
4

3 回答 3

5

如果有人正在阅读此内容,则不,正确的方法是在连接打开时触发以下行:

public Entities()
    : base("name=Entities")
{        

    ctx.Database.Connection.StateChange += Connection_StateChange;
    ...
}

    private void Connection_StateChange(object sender, StateChangeEventArgs e)
    {
        if (e.OriginalState == ConnectionState.Open || e.CurrentState != ConnectionState.Open)
            return;

       this.Database.ExecuteSqlCommand("ALTER SESSION SET NLS_COMP=ANSI");

    }
于 2015-09-27T10:10:32.110 回答
2

你可以使用 Database.Connection.StateChange 方法

    public AtomContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
        this.Database.Connection.StateChange += Connection_StateChange;
    }

    void Connection_StateChange(object sender, StateChangeEventArgs e)
    {
        if (e.OriginalState == ConnectionState.Open || e.CurrentState != ConnectionState.Open)
            return;

        IDbConnection connection = ((EntityConnection)((IObjectContextAdapter)this).ObjectContext.Connection).StoreConnection;
        using (IDbCommand command = connection.CreateCommand("ALTER SESSION SET NLS_LANGUAGE=TURKISH"))
            command.ExecuteNonQuery();

        using (IDbCommand command = connection.CreateCommand("ALTER SESSION SET NLS_COMP = LINGUISTIC"))
            command.ExecuteNonQuery();

        using (IDbCommand command = connection.CreateCommand("ALTER SESSION SET NLS_SORT=TURKISH_AI"))
            command.ExecuteNonQuery();
    }

于 2016-05-15T00:46:26.673 回答
0

另一个选项是“LOGON TRIGGER ON SCHEMA”。但是您是否强制 DBA 创建它是值得怀疑的。登录触发器被认为是“危险的”。

于 2013-01-17T18:16:03.137 回答