拦截并更改应用程序生成的 sql 查询

Intercept and alter sql query generated by the Application

我有一个插件正在查询和获取一些数据的情况,我无法将插件中的查询更改为一个 DLL。 我已经使用 SQL 探查器检查了它正在执行的查询,并且根据我们的要求,我们已经更改了该区域的数据库模式,因此破坏了该插件查询。

有什么方法可以截取并修改查询吗?

就像我们在 JS 框架中所做的那样 Angular 我们有拦截器来接收每个调用并在 header 中添加令牌,我们是否有类似的东西来拦截所有传出 SQL调用并改变它?

也许中间件可以像我一样在这里工作。NET-Core 或某种处理程序?

可以在拦截器中更改查询。

EF 6

实施IDbCommandInterceptor,例如:

class EFCommandInterceptor: IDbCommandInterceptor
{

    public void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        // Manipulate the command text, etc. here...
        command.CommandText += " OPTION (OPTIMIZE FOR UNKNOWN)";
    }

    ...

注册:

public class FE6CodeConfig : DbConfiguration
{
    public FE6CodeConfig()
    {
        this.AddInterceptor(new EFCommandInterceptor());
    }
}

查看更多详情here

EF 核心

EF Core 也有拦截器 nowadays。您需要 EF Core 3 或更高版本。

虽然 EF Core 3 需要 .NET Standard 2.1(因此 .NET Core 3 及更高版本),但 EF Core 3.1 支持 .NET Standard 2.0,因此 .NET Core 2 和 . NET 框架 4.6.1+

继承DbCommandInterceptor,例如

public class HintCommandInterceptor : DbCommandInterceptor
{
    public override InterceptionResult ReaderExecuting(
        DbCommand command,
        CommandEventData eventData,
        InterceptionResult result)
    {
        // Manipulate the command text, etc. here...
        command.CommandText += " OPTION (OPTIMIZE FOR UNKNOWN)";
        return result;
    }
}

注册:

services.AddDbContext(b => b
    .UseSqlServer(connectionString)
    .AddInterceptors(new HintCommandInterceptor())