Access DataContext behind IQueryable

心不动则不痛 提交于 2019-12-18 13:03:06

问题


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

If so, how?


回答1:


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;
}


来源:https://stackoverflow.com/questions/3208439/access-datacontext-behind-iqueryable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!