Is it possible to access the DataContext object behind an IQueryable?
If so, how?
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With