【问题标题】:Is it possible to get query string before stored procedure execution in EF?是否可以在 EF 中执行存储过程之前获取查询字符串?
【发布时间】:2017-10-31 21:59:15
【问题描述】:

是否可以在执行之前获取实体框架为存储过程生成的查询? 例如。调用 sp

context.Test(1)

获取字符串

执行 [dbo].Test 1

执行之前

【问题讨论】:

  • 您使用哪个 EF 版本?
  • @MarcinZablocki 6

标签: c# sql entity-framework stored-procedures


【解决方案1】:

如果您使用的是 Entity Framework 6,那么您可以使用 查询拦截器 在 SQL 生成和 SQL 执行之间注入代码。它是通过实现IDbInterceptor 来完成的。您可以附加到以下“事件”:

namespace System.Data.Entity.Infrastructure.Interception
{
  public interface IDbCommandInterceptor : IDbInterceptor
  {
    void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext);

    void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext);

    void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext);

    void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext);

    void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext);

    void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext);
  }
}

您可以编写实现上述接口的自定义拦截器,然后通过调用将其添加到您的 EF 中:

DbInterception.Add(new &lt;your implementation&gt;());

这里还有其他查看Entity Framework生成的SQL的建议:How do I view the SQL generated by the Entity Framework?,不过要看你是想只查看SQL还是在执行前执行一些动作。

【讨论】:

  • 好的。谢谢,但是可以让查询字符串修改它然后执行吗?所以我可以默认以某种方式停止执行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-20
  • 2017-11-22
  • 1970-01-01
  • 2020-12-13
  • 2010-12-09
  • 1970-01-01
  • 2010-11-03
相关资源
最近更新 更多