实体框架7拦截器

时间:2016-03-03 16:58:54

标签: multi-tenant entity-framework-core interception

我有一个多租户应用程序,如何在Entity Framework 7中使用拦截?

在Entity Framework 6中,使用System.Data.Entity.Infrastructure.Interception存在拦截,但在实体框架的版本7中找不到。

这是一个例子 - > https://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-entity-framework-row-level-security/

3 个答案:

答案 0 :(得分:1)

拦截尚未在EFCore中实施。这是一个积压项目(见https://github.com/aspnet/EntityFramework/wiki/Roadmap

答案 1 :(得分:0)

虽然EF Core没有拦截器,但可以执行QueryFilters以确保所有查询都按租户ID进行过滤。

Gunnar Peipman有很多文章可以帮助您了解如何将QueryFilters用于多租户方案。 http://gunnarpeipman.com/2017/08/ef-core-global-query-filters/

答案 2 :(得分:0)

我有些问题。 在EF Core中,您可以使用拦截器,这里有一些可能有用的示例代码:

using System.Data.Common;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.DiagnosticAdapter;

public class CommandListener
{

    [DiagnosticName("Microsoft.EntityFrameworkCore.Database.Command.CommandExecuting")]
    public void OnCommandExecuting(DbCommand command, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, bool async, DateTimeOffset startTime)
    {
        //call security or other methods here. 
    }

    [DiagnosticName("Microsoft.EntityFrameworkCore.Database.Command.CommandExecuted")]
    public void OnCommandExecuted(object result, bool async)
    {
       //call security or other methods here. 
    }
}

在您的存储库的构造函数中,您可以执行挂钩

    var listener = _context.GetService<DiagnosticSource>();
    (listener as DiagnosticListener).SubscribeWithAdapter(new CommandListener());

现在,当您查询dbContext时,例如:

_context.employees.Where(...

然后在返回此查询之前,执行上述方法OnCommandExecuting和OnCommandExecuted。

所以你可以在某种程度上模仿EF Core中的SaveChanges覆盖。

但是需要注意的一件重要事情是,在OnCommandExecuting和OnCommandExecuted方法中无法访问查询的返回结果集。

相关问题