3

I Have a Multi-Tenant application and how can I use Interception in Entity Framework 7?

In Entity Framework 6, exists Interception using System.Data.Entity.Infrastructure.Interception, but don't find in version 7 of the Entity Framework.

Here's an example -> https://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-entity-framework-row-level-security/

Sérgio R Silva
  • 101
  • 1
  • 4

3 Answers3

1

Interception isn't implemented yet in EFCore. It is a backlog item (see https://github.com/aspnet/EntityFramework/wiki/Roadmap)

Polan
  • 11
  • 1
0

Although EF Core does not have Interceptors, it is possible to perform QueryFilters to ensure that all queries are filtered by the tenant id.

Gunnar Peipman has a number of articles that can help you understand how to use QueryFilters for a Multi-Tenant scenario. http://gunnarpeipman.com/2017/08/ef-core-global-query-filters/

Lutti Coelho
  • 2,134
  • 15
  • 31
0

I have somewhat some issue. In EF Core you can use interceptors, here's some sample code that may be of use:

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. 
    }
}

In the constructor of your repository you do the hooking

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

Now when you query your dbContext e.g.:

_context.employees.Where(...

Then before this query is returned the above methods OnCommandExecuting and OnCommandExecuted are executed.

So you can somewhat imitate the override of SaveChanges in EF Core.

However one important thing to note is that the return result set from the query is not accessible in the OnCommandExecuting and OnCommandExecuted methods.

Mohammad
  • 1,498
  • 2
  • 12
  • 15