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