简体   繁体   English

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

[英]Intercept and alter sql query generated by the Application

I have a situation where a plugin is querying and getting some data, I cannot change the query in plugin as its a DLL.我有一个插件正在查询并获取一些数据的情况,我无法将插件中的查询更改为它的 DLL。 I have checked with the SQL profiler what query it is making and as per our requirement we have changed the database schema in that area, hence breaking that plugin query.我已经用 SQL 探查器检查了它正在执行的查询,并且根据我们的要求,我们已经更改了该区域的数据库模式,因此破坏了该插件查询。

Is there any way to intercept the query and alter it?有没有办法拦截查询并改变它?

Just like how we do in JS framework like Angular that we have interceptor to receive each call and add token in the header, do we have something like that to intercept all outgoing SQL calls and alter it?就像我们在 Angular 等 JS 框架中所做的那样,我们有拦截器来接收每个调用并在标头中添加令牌,我们是否有类似的东西来拦截所有传出的 SQL 调用并更改它?

Maybe middleware can work here as I am in .NET-Core or some kind of handler?也许中间件可以像我在 .NET-Core 或某种处理程序中一样在这里工作?

The query could be changed in a interceptor.可以在拦截器中更改查询。

EF 6英孚 6

Implement IDbCommandInterceptor , for example:实现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)";
    }

    ...

Register:登记:

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

See more details here 在此处查看更多详细信息

EF Core英孚核心

Also EF Core has interceptors nowadays . 现在EF Core 也有拦截器。 You need EF Core 3 or later.您需要 EF Core 3 或更高版本。

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

Inherit of DbCommandInterceptor , eg继承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;
    }
}

Register:登记:

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

我一直在寻找解决方案,除了 appsetting 或 web.config 之外没有修改任何代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM