還有的IQueryable<T>
在框架的實現 - MSDN: EnumerableQuery<T>
如果您可以使用此客戶端上,以構建查詢,你可以從IQueryable<T>.Expression
財產整個表達式樹。
您將不得不測試它以查看它是否適用於該表達式樹序列化器。
var iQueryable = new EnumerableQuery<Model>(Enumerable.Empty<Model>());
var query = iQueryable.Include(...).Where(...).OrderBy(...);
var expressionTree = query.Expression;
然後,您可以序列化表達式,將它噴射到電線上,然後反序列化它。
然後問題是表達式樹是基於EnumerableQuery<T>
。
所以,你需要與你的IQueryable<T>
源代替從你的真實DbContext
這得到了位凌亂,但我已經寫了使用ExpressionVisitor:
IQueryable FixupExpressionTree(ObjectContext ctx, Type entityType, Expression expression)
{
var tObjectContext = ctx.GetType();
var mCreateObjectSetOpen = tObjectContext.GetMethod("CreateObjectSet", new Type[ 0 ]);
var mCreateObjectSetClosed = mCreateObjectSetOpen.MakeGenericMethod(entityType);
var objectQuery = (ObjectQuery) mCreateObjectSetClosed.Invoke(ctx, null);
var eFixed = new Visitor(objectQuery, entityType).Visit(expression);
var qFixed = ((IQueryable) objectQuery).Provider.CreateQuery(eFixed);
return qFixed;
}
和ExpressionVisitor
實現本身:
public class Visitor : ExpressionVisitor
{
ObjectQuery _Source = null;
Type _EntityType = null;
public Visitor(ObjectQuery source, Type entityType) { _Source = source; _EntityType = entityType; }
protected override Expression VisitConstant(ConstantExpression node)
{
if (!node.Type.Name.Contains("EnumerableQuery")) return base.VisitConstant(node);
var eConstantInstance = Expression.Constant(_Source);
var eConstantArgument = Expression.Constant(MergeOption.AppendOnly);
var tObjectQueryOpen = typeof(ObjectQuery<>);
var tObjectQueryClosed = tObjectQueryOpen.MakeGenericType(_EntityType);
var eMergeAsMethod = tObjectQueryClosed.GetMethod("MergeAs", BindingFlags.Instance | BindingFlags.NonPublic);
return Expression.Call(eConstantInstance, eMergeAsMethod, eConstantArgument);
}
}
Calli NG,這是直截了當:
Type entityType = ...
Expression expression = ...
DbContext db = ...
ObjectContext ctx = ((IObjectContextAdapter) db).ObjectContext;
IQueryable query = FixupExpressionTree(ctx, entityType, expression);
我知道這是不是一個回答你的問題,但是從經驗,我不會這麼做,而是寫竭誠爲企業服務。您增加了複雜性,並允許您的客戶端以不良的查詢來降低系統性能。 – 2013-04-23 11:05:11