【发布时间】:2017-10-31 21:59:15
【问题描述】:
是否可以在执行之前获取实体框架为存储过程生成的查询? 例如。调用 sp
context.Test(1)
获取字符串
执行 [dbo].Test 1
但在执行之前
【问题讨论】:
-
您使用哪个 EF 版本?
-
@MarcinZablocki 6
标签: c# sql entity-framework stored-procedures
是否可以在执行之前获取实体框架为存储过程生成的查询? 例如。调用 sp
context.Test(1)
获取字符串
执行 [dbo].Test 1
但在执行之前
【问题讨论】:
标签: c# sql entity-framework stored-procedures
如果您使用的是 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 <your implementation>());
这里还有其他查看Entity Framework生成的SQL的建议:How do I view the SQL generated by the Entity Framework?,不过要看你是想只查看SQL还是在执行前执行一些动作。
【讨论】: