Can I fire an event on connect database in Entity Framework Core?

前端 未结 2 1436
执笔经年
执笔经年 2021-01-14 03:41

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

2条回答
  •  一生所求
    2021-01-14 03:57

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

提交回复
热议问题