我已经实现了一个基本的(天真的?)LINQ 提供程序,它可以满足我的目的,但是我想解决一些怪癖,但我不确定如何解决。例如:
// performing projection with Linq-to-Objects, since Linq-to-Sage won't handle this:
var vendorCodes = context.Vendors.ToList().Select(e => e.Key);
我的IQueryProvider
实现有一个如下所示的CreateQuery<TResult>
实现:
public IQueryable<TResult> CreateQuery<TResult>(Expression expression)
{
return (IQueryable<TResult>)Activator
.CreateInstance(typeof(ViewSet<>)
.MakeGenericType(elementType), _view, this, expression, _context);
}
显然,当Expression
is aMethodCallExpression
和TResult
is a时,这会窒息string
,所以我想我会执行该死的事情:
public IQueryable<TResult> CreateQuery<TResult>(Expression expression)
{
var elementType = TypeSystem.GetElementType(expression.Type);
if (elementType == typeof(EntityBase))
{
Debug.Assert(elementType == typeof(TResult));
return (IQueryable<TResult>)Activator.CreateInstance(typeof(ViewSet<>).MakeGenericType(elementType), _view, this, expression, _context);
}
var methodCallExpression = expression as MethodCallExpression;
if(methodCallExpression != null && methodCallExpression.Method.Name == "Select")
{
return (IQueryable<TResult>)Execute(methodCallExpression);
}
throw new NotSupportedException(string.Format("Expression '{0}' is not supported by this provider.", expression));
}
因此,当我运行时,var vendorCodes = context.Vendors.Select(e => e.Key);
我最终会陷入private static object Execute<T>(Expression,ViewSet<T>)
重载,这会打开最里面的过滤器表达式的方法名称,并在底层 API 中进行实际调用。
现在,在这种情况下,我正在传递Select
方法调用表达式,因此过滤器表达式是null
并且我的switch
块被跳过 - 这很好 - 我被困在这里:
var method = expression as MethodCallExpression;
if (method != null && method.Method.Name == "Select")
{
// handle projections
var returnType = method.Type.GenericTypeArguments[0];
var expType = typeof (Func<,>).MakeGenericType(typeof (T), returnType);
var body = method.Arguments[1] as Expression<Func<T,object>>;
if (body != null)
{
// body is null here because it should be as Expression<Func<T,expType>>
var compiled = body.Compile();
return viewSet.Select(string.Empty).AsEnumerable().Select(compiled);
}
}
我需要做什么MethodCallExpression
才能将其传递给 LINQ-to-Objects 的Select
方法?我什至正确地接近这个?