Entity Framework 7 拦截器

3
3个回答

1

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 方法中无法访问查询的返回结果集。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接