使用SESSION_CONTEXT的实体框架核心行级安全性 [英] Entity Framework Core Row Level Security using SESSION_CONTEXT

查看:73
本文介绍了使用SESSION_CONTEXT的实体框架核心行级安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用使用ASP.NET Core和Entity Framework 7(Core)的行级安全性来编写多租户应用程序。
因为我的数据库托管在Microsoft SQL Server上,所以我使用了强制执行RLS的方法。

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.

现在,我需要在SESSION_CONTEXT中设置所需的tenant_id。

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

我面临的第一个问题是使用EF7运行存储过程。解决方法似乎是:

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

使用以上命令,我可以清楚地看到SESSION_CONTEXT已成功设置。现在,我希望看到根据我在SESSION_CONTEXT中设置的租户对相同上下文的下一个查询进行过滤。

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;

不幸的是,结果与预期不符。行为就像在设置SESSION_CONTEXT之前已检索行。

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

这是由于EF7的频繁加载引起的吗? EF7是否使用现金数据?
我该如何克服呢?

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

我希望能够为SESSION_CONTEXT设置任何所需的值,并且该值将保留在上下文中,直到更改或直到连接关闭。

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.

推荐答案

我很想通过阅读本文


EF6和未来版本采取的方法是,如果调用
的代码选择通过调用
context.Database.Connection.Open()打开连接,则这样做有充分的理由,因此框架将假设它想要控制打开
和关闭连接的操作,并且不再自动关闭连接

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.

解决方案是在执行任何EF命令之前打开连接。

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

context.Database.Connection.Open();

这篇关于使用SESSION_CONTEXT的实体框架核心行级安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆