Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access DataContext behind IQueryable

Is it possible to access the DataContext object behind an IQueryable?

If so, how?

like image 786
Alex Avatar asked Jul 08 '10 22:07

Alex


People also ask

What is DataContext in LINQ?

Remarks. The DataContext is the source of all entities mapped over a database connection. It tracks changes that you made to all retrieved entities and maintains an "identity cache" that guarantees that entities retrieved more than one time are represented by using the same object instance.

What is LINQ SQL in C#?

LINQ to SQL is a component of . NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objects. Relational data appears as a collection of two-dimensional tables (relations or flat files), where common columns relate tables to each other.


1 Answers

DataContext is specific to LINQ to SQL, so presumably you're talking about LINQ to SQL queries? If so, there's no safe way to do this - you have to resort to a hack such as using reflection to retrieve the private "context" field of the underlying DataQuery object:

static DataContext GetContext (IQueryable q)
{
  if (!q.GetType().FullName.StartsWith ("System.Data.Linq.DataQuery`1")) return null;
  var field = q.GetType().GetField ("context", BindingFlags.NonPublic | BindingFlags.Instance);
  if (field == null) return null;
  return field.GetValue (q) as DataContext;
}
like image 77
Joe Albahari Avatar answered Oct 26 '22 23:10

Joe Albahari