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.