Execute SQL Alter commands for every session with Entity Framework 5 talking to Oracle 11g

六月ゝ 毕业季﹏ 提交于 2019-12-01 04:55:39

问题


I have a requirement to execute some SQL commands at the start of every database session. I am using Entity Framework 5 via DbContext talking to a Oracle 11g database.

I would like to execute:

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

at the start of an session creation to get case insensitive searching.
How best could I go about this?

I've put the commands in the constructor of dbContext, but have only simple unit test and it does appear to work. But unsure if this is right thing to do

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

回答1:


If anyone is reading this, no, the right way is doing it on connection open triggered down the line of:

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

    }



回答2:


you can use Database.Connection.StateChange method

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

entityframeworkef6oracledbcontextsession




回答3:


The other option would be a "LOGON TRIGGER ON SCHEMA". But it's questionable whether you force DBA's to create it. Logon triggers are considered to be "dangerous".



来源:https://stackoverflow.com/questions/14372297/execute-sql-alter-commands-for-every-session-with-entity-framework-5-talking-to

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