简体   繁体   中英

Entity Framework Core Row Level Security using SESSION_CONTEXT

I am writing a multi-tenant application using Row Level Security using ASP.NET Core and Entity Framework 7 (Core). Since my database is hosted on Microsoft SQL Server, I have used this method to enforce RLS.

Now all I need is to set desired tenant_id in the SESSION_CONTEXT.

First problem I faced was to run a stored procedure using EF7. A solution seems to be:

var resp = context.Set<SessionVars>().FromSql(
          "EXECUTE sp_set_session_context @key = N'my_tenant', @value = {0};
           SELECT * FROM mySessionVars", desiredTenant).ToList();

Using the above command I can clearly see that the SESSION_CONTEXT is successfully set. Now I expect to see that the next queries on the same context are filtered according to the tenant I set in SESSION_CONTEXT.

int visibleRows = context.MyModel.ToList().Count;

Unfortunately the results are not as expected. It behaves like the rows were retrieved before SESSION_CONTEXT was set.

Is this caused by the Eager Loading of EF7? IS EF7 using cashed data? How can I overcome this?

I expect to be able to set any value I want for the SESSION_CONTEXT and this to be hold in the context until changed or until connection is closed.

I was abble to found an answer mysels by reading this article ,

EF6 and future versions we have taken the approach that if the calling code chooses to open the connection by calling context.Database.Connection.Open() then it has a good reason for doing so and the framework will assume that it wants control over opening and closing of the connection and will no longer close the connection automatically.

The solution is to open the connection before executing any EF command.

context.Database.Connection.Open();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM