Entity Framework - Setting session_context using IDbConnectionInterceptor

后端 未结 2 688
梦如初夏
梦如初夏 2021-02-10 00:46

I\'m following this tutorial in order to use Row Level security in SQL Server via Entity Framework 6 CodeFirst. The tutorial code sample shows how to use IDbConnectionIntercepto

2条回答
  •  遇见更好的自我
    2021-02-10 01:06

    You can use the Connection_StateChaned event of your DbContext if you are using EF like so.

     static void Main(string[] args)
        {               
            using (var db = new AdventureWorks2016CTP3Entities())
            {
                db.Database.Connection.StateChange += Connection_StateChange;
                db.Database.Log = (log) => System.Diagnostics.Debug.WriteLine(log);
    
                var purchase = db.SalesOrderHeader.Select(i => i.SalesPersonID);
    
                foreach (var m in purchase)
                {
                    Console.WriteLine(m);
                }
            }
    
        }
    
        private static void Connection_StateChange(object sender, System.Data.StateChangeEventArgs e)
        {
            if(e.CurrentState == System.Data.ConnectionState.Open)
            {
                var cmd = (sender as System.Data.SqlClient.SqlConnection).CreateCommand();
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = "exec sp_set_session_context 'UserId', N'290'";
    
                cmd.ExecuteNonQuery();
            }
        }
    

提交回复
热议问题