Csharp/C#教程:从IDbCommandInterceptor的实现中获取DbContext分享


从IDbCommandInterceptor的实现中获取DbContext

我正在使用IDbCommandInterceptor实现:

 public class MyInterceptor : IDbCommandInterceptor { public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) { var context = interceptionContext.DbContexts.FirstOrDefault(); } public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) { } public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) { } public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) { } public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) { } public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) { } } 

注入:

 public class TestContext : System.Data.Entity.DbContext { // … public TestContext() : base("TestConnectionString") { Database.SetInitializer(null); DbInterception.Add(new MyInterceptor()); } } 

(也在静态构造函数中尝试过)。

但是interceptionContext.DbContexts总是空的。 如何获取执行上下文的实例? 可能吗?

这并没有完全回答我的问题,但我在Entity Framework文档中找到的解释是最准确的:

值得注意的是,拦截上下文是提供上下文信息的最佳努力。 但是,在某些极端情况下,您期望在那里获得的某些信息可能不存在。 这是因为EF具有无法轻易更改的代码路径,并且不包含可能预期的信息。 例如,当EF对提供者进行调用时,提供者不知道正在使用的DbContext。 如果EF之外的提供者决定调用ExecuteNonQuery,那么可能会发生两件事:

幸运的是,这种情况很少见,对大多数应用程序来说可能不是问题。

我不知道我的情况是如何“罕见”但也许我做错了…

上述就是C#学习教程:从IDbCommandInterceptor的实现中获取DbContext分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/961204.html

(0)
上一篇 2021年11月25日
下一篇 2021年11月25日

精彩推荐