Access DbContext from IQueryable
Asked Answered
D

1

7

I am trying to implement a caching pattern which may need to utilise Redis. The problem with this pattern is that I need to disable Configuration.ProxyCreationEnabled and then re-enable it afterwards to avoid any issues across a web farm.

What I would like to do is access the DbContext from the IQueryable so I can do this once instead of everywhere. The easiest way to do this is to pass the DbContext being used into my caching extension, however I came across this post:

Access DataContext behind IQueryable

Is there a way of accessing the DbContext in a similar manner to the link above using EF 4.1 Code Fist (DbSet's, etc)?

I have tried to find this myself but have struggled to find the base class from the referenced DbSet in the IQueryable using reflection.

Diskin answered 5/9, 2011 at 15:33 Comment(0)
M
8

The solution mentioned in Access DataContext behind IQueryable is a hack and should not be used. It relies on the name of a private member variable in the class implementing IQueryable. This means that the implementing class could change in a future release of EF/.NET Framework and break your code. Since the DbContext is not accessible through the IQueryable interface, you should pass it into your caching extension to avoid making assumptions about the IQueryable implementation. Doing so will also more clearly establish the dependency on the DbContext in your caching interface, instead of burying it in the implementation.

Musket answered 5/9, 2011 at 16:9 Comment(1)
Thanks for that. Was coming to a similar conclusion, but was thinking it would be nice to abstract the implementation.Diskin

© 2022 - 2024 — McMap. All rights reserved.