本系列原创博客代码已在EntityFramework6.0.0测试通过,转载请标明出处

有时候我们要通过IQueryable获取所在的DbContext信息,这是完全可以的。

以下代码从个人开源框架中抽取而出

using System;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.Interception;
using System.Linq;
using System.Reflection; /*
* CopyRight ©2017 All Rights Reserved
* 作者:Rex Sheng
*/
namespace SuperNet.EntityFramework.Extensions
{
public static class IQueryableExtensions
{
public static DbContext GetDbContext<TEntity>(this IQueryable<TEntity> query) where TEntity : class
{
ObjectQuery<TEntity> objectQuery = null;
DbQuery<TEntity> dbQuery = null;
if(query is ObjectQuery<TEntity>)
{
objectQuery = (ObjectQuery<TEntity>)query;
}
else
{
if(query is DbQuery<TEntity>)
{
dbQuery = (DbQuery<TEntity>)query;
var propers = dbQuery.GetType().GetProperty("InternalQuery", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (propers == null)
{
throw new Exception("未能从IQueryable表达式找到DbContext。您确定此表达式来自Ef DbContext吗?");
}
var obj = propers.GetValue(dbQuery, null);
propers = obj.GetType().GetProperty("ObjectQuery", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (propers == null)
{
throw new Exception("未能从IQueryable表达式找到DbContext。您确定此表达式来自Ef DbContext吗?");
}
objectQuery = propers.GetValue(obj, null) as ObjectQuery<TEntity>;
if (objectQuery == null)
{
throw new Exception("未能从IQueryable表达式找到DbContext。您确定此表达式来自Ef DbContext吗?");
}
}
else
{
throw new Exception("未能从IQueryable表达式找到DbContext。您确定此表达式来自Ef DbContext吗?");
}
}
return objectQuery.Context.GetDbContext();
} }
}
05-21 04:29