我可以在Entity Framework Core中的连接数据库上触发事件吗?

我可以在Entity Framework Core中的连接数据库上触发事件吗?

问题描述:

我只有一个DbContext可以正常访问我的Postgresql数据库,但是当连接会话从DB开始时,我需要运行一个小的SQL命令。每次互动我都需要这样做。更具体地说,它是用于设置记录用户名的会话变量的功能。

I've one DbContext with all working to access my Postgresql DB, but I need to run one little SQL command when connection session starts with DB. I need to do this for every interaction. To be more specific, it's a function for set a session variable with user name logged.

是否可以在EF Core中做一些处理?

It's possible to do something to handle that in EF Core?

-解决方案-

我没有意识到我可以像Bricelam所说的那样直接在OnConfiguring中指定一个连接。我需要在每个连接中都这样做,因为它是每个会话的变量。它不是数据库的用户名,而是应用程序日志记录系统的用户名。

I didn't realized that I could specify a connection directly in OnConfiguring like bricelam says. I need to do this in every connection because it's a variable by session. It's not a user name for database but for application logging system.

    public ContratoInternetDbContext(DbContextOptions<ContratoInternetDbContext> options, 
        IOptions<AppSettings> configs)
        : base(options)
    {
        _appSettings = configs.Value;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var conn = new NpgsqlConnection(_appSettings.ConnectionString);
        conn.StateChange += (snd, e) =>
        {
            if ((e.CurrentState != e.OriginalState) && (e.CurrentState == ConnectionState.Open))
            {
                _cmmSetVarSession.ExecuteNonQuery();
            }
        };

        optionsBuilder.UseNpgsql(conn);

        _cmmSetVarSession = conn.CreateCommand();
        _cmmSetVarSession.CommandText = "select sessao_set_var('usuario', 'CENTRAL_CLIENTE')";
    }


您应该可以通过将连接传递到您的 DbContext 并挂钩 StateChange 事件:(请原谅SQLite示例。我知道您

You should be able to do it by passing a connection into your DbContext and hooking the StateChange event: (Please forgive the SQLite example. I know you said PostgreSQL.)

var connection = new SqliteConnection(connectionString);
_connection.StateChange += (sender, e) =>
{
    if (e.OriginalState != ConnectionState.Open)
        return;

    var senderConnection = (DbConnection)sender;

    using (var command = senderConnection.CreateCommand())
    {
        command.Connection = senderConnection;
        command.CommandText = "-- TODO: Put little SQL command here.";

        command.ExecuteNonQuery();
    }
};

optionsBuilder.UseSqlite(connection);