code-first - 从 IQueryable 访问 DbContext

标签 code-first ef4-code-only

我正在尝试实现可能需要利用 Redis 的缓存模式。这种模式的问题是我需要禁用 Configuration.ProxyCreationEnabled 然后重新启用它以避免跨网络场的任何问题。

我想做的是从 IQueryable 访问 DbContext ,这样我就可以一次而不是到处执行此操作。最简单的方法是将正在使用的 DbContext 传递到我的缓存扩展中,但是我遇到了这篇文章:

Access DataContext behind IQueryable

有没有一种方法可以使用 EF 4.1 Code Fist(DbSet 等)以与上述链接类似的方式访问 DbContext?

我试图自己找到这个,但很难使用反射从 IQueryable 中引用的 DbSet 中找到基类。

最佳答案

Access DataContext behind IQueryable 中提到的解决方案是一个黑客,不应该使用。它依赖于实现 IQueryable 的类中的私有(private)成员变量的名称。这意味着实现类可能会在 EF/.NET Framework 的 future 版本中发生更改并破坏您的代码。由于无法通过 IQueryable 接口(interface)访问 DbContext,因此应将其传递到缓存扩展中以避免对 IQueryable 实现做出假设。这样做还将更清楚地在缓存接口(interface)中建立对 DbContext 的依赖关系,而不是将其埋在实现中。

关于code-first - 从 IQueryable 访问 DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7310101/

相关文章:

c# - 结合 EF Power Tools 和 .edmx 生成 CodeFirst Class 和 DB

asp.net-mvc - EF4、MVC 3、Azure 和 Code First 或传统

asp.net - Linq to Entity(EF 4.1) 的匿名类型?

entity-framework-4 - Entity Framework 4 的流畅映射验证

linq - 按名称检索实体对象 - LINQ to Entities,EF 4.0

entity-framework - Entity Framework CTP 5 一对一映射

entity-framework - 如何首先使用实体​​框架代码更新一行?

entity-framework-4 - Entity Framework 4 Code First 和 new() 运算符

c# - Entity Framework : Remove and Add entities with same key in a single request

entity-framework - EF4 代码优先 : To Include or to not Include the Foreign Keys in the model when setting up an Association