12

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

If so, how?

Alex
  • 75,813
  • 86
  • 255
  • 348

1 Answers1

14

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;
}
Joe Albahari
  • 30,118
  • 7
  • 80
  • 91
  • 1
    You mentioned this is a hack, but it should not be recommended even as such. Accessing private members through reflection is not a good practice, and it will produce brittle code. Doing so also hides the dependency between the calling code and the DataContext class. – Brent M. Spell Sep 05 '11 at 18:39
  • +1 as this can actually be used 'as a hack' to access the context when someone returns IQueryable and then has full access to query away : ) – Adam Tuliper Jan 12 '12 at 15:42
  • 1
    A small addition. System.Data.Linq.Table<> may also be behing IQueryable interface. Code: string typeName = q.GetType().FullName; if (!typeName.StartsWith("System.Data.Linq.DataQuery`1", StringComparison.Ordinal) && !typeName.StartsWith("System.Data.Linq.Table`1", StringComparison.Ordinal)) { return null; } – Dmitry Dzygin Mar 16 '12 at 10:36
  • could this be used to dynamically tell the IQueryable to use a different DataContext? – nitewulf50 Mar 19 '13 at 20:56
  • @nitewulf50 sure why not, just use the setter – AgentFire May 11 '19 at 15:59