问题描述
我正在使用 IDbCommandInterceptor
实现:
public class MyInterceptor : IDbCommandInterceptor
{
public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
var context = interceptionContext.DbContexts.FirstOrDefault();
}
public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
}
public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
}
public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
}
public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
}
public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
}
}
由此注入:
public class TestContext : System.Data.Entity.DbContext
{
// …
public TestContext()
: base("TestConnectionString")
{
Database.SetInitializer<TestContext>(null);
DbInterception.Add(new MyInterceptor());
}
}
(也在静态构造函数中尝试过).
(also tried in static constructor).
但 interceptionContext.DbContexts
始终为空.如何获取执行上下文的实例?有可能吗?
But interceptionContext.DbContexts
is always empty. How can I get an instance of executing context? Is it possible?
推荐答案
这并没有完全回答我的问题,而是我在 实体框架文档 是最准确的:
This does not fully answer my question but the explanation I found in Entity Framework documentation was the most accurate:
值得注意的是,拦截上下文是提供上下文信息的最大努力.但是,在某些极端情况下,您可能不希望出现某些信息.这是因为 EF 具有不易更改的代码路径,并且不包含预期的信息.例如,当 EF 调用提供程序时,提供程序不知道正在使用的 DbContext.如果 EF 之外的提供者决定调用 ExecuteNonQuery,那么可能会发生两件事:
It’s worth noting that the interception context is a best effort to provide contextual information. However, in some corner cases some information that you would expect to be there may not be there. This is because EF has code paths that cannot easily be changed and do not include information that might be expected. For example, when EF makes a call into a provider, the provider has no knowledge of the DbContext being used. If that provider, outside of EF, decides to call ExecuteNonQuery, then two things might happen:
- 首先,提供者可以直接调用,完全避免 EF 拦截.(这是在 EF 级别进行拦截而不是在堆栈中的较低级别进行拦截的结果.如果拦截在堆栈中较低,那就太好了,但不幸的是,这超出了 EF 团队的控制范围.)
- 如果提供程序知道 EF 拦截,则它可以通过 EF 拦截器调度 ExecuteNonQuery 调用.这意味着任何注册的拦截器都会收到通知并且可以采取适当的行动.这就是 SQL Server 和 SQL Server Compact 提供程序所做的.但是,即使提供者这样做,所使用的 DbContext 也很可能不会包含在拦截上下文中,因为提供者不知道它,并且允许这样做的更改会破坏定义良好的提供者 API.
幸运的是,这种情况很少见,对于大多数应用程序来说可能不会成为问题.
Luckily this kind of situation is rare and will likely not be an issue for most applications.
我不知道我的情况有多罕见",但也许我做错了什么……
I don't know how my situation is "rare" but maybe I am doing something wrong…
这篇关于从 IDbCommandInterceptor 的实现中获取 DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!