Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access DbContext from IQueryable

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.

like image 583
didiHamman Avatar asked Sep 05 '11 15:09

didiHamman


1 Answers

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.

like image 143
Brent M. Spell Avatar answered Nov 04 '22 04:11

Brent M. Spell