Expression.Call - 调用linq扩展名:FirstOrDefault,Where [英] Expression.Call - Calling linq extension: FirstOrDefault, Where
问题描述
我正在尝试动态创建以下内容,但是在调用扩展方法FirstOrDefault时遇到问题
I am trying to create the following dynamically, however I am having problems calling the extension method "FirstOrDefault"
using(var context = new Entities())
{
var list = context.Engines.Include("Cars").Select(e => e.Cars.FirstOrDefault()).ToList();
}
我有以下
Expression parameter = Expression.Parameter(typeof(Engine), "e");
Expression property = Expression.Property(parameter, "Cars");
- parameter = {e}
- property = {e.Cars}
这些都不错,但是当我尝试调用FirstOrDefault方法时遇到问题
Those are good, but I am encountering a problem when I try and call the FirstOrDefault method
var result = Expression.Call(typeof(Queryable), "FirstOrDefault", new type[] { typeof(Car)}, property);
我想获得
- result = {e.Cars.FirstOrDefault()}
但是我收到了一个InvalidOperationException
but I am getting an InvalidOperationException
上没有通用方法'FirstOrDefault'类型'System.Linq.Queryable'是
与提供的类型$ b $兼容b参数和参数。如果
方法是非泛型的,则不应该提供类型
参数。
No generic method 'FirstOrDefault' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.
任何帮助都会很多赞赏。
Any help would be much appreciated.
谢谢。 Adam
推荐答案
你确定 e.Cars
是一个 IQueryable< T> ?
如果没有,您不能将其传递到 Queryable.FirstOrDefault< T( IQueryable< T>)。
If not, you can't pass it to Queryable.FirstOrDefault<T>(IQueryable<T>).
如果是 IEnumerable< T> ,更改代码以调用 Enumerable.FirstOrDefault< T>(IEnumerable< T):
If it's an IEnumerable<T>, change your code to call Enumerable.FirstOrDefault<T>(IEnumerable<T>):
var result =
Expression.Call(
typeof(Enumerable),
"FirstOrDefault",
new Type[] { TypeSystem.GetElementType(property.Type) },
property);
这篇关于Expression.Call - 调用linq扩展名:FirstOrDefault,Where的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!