使用表达式树在linq中创建实体的自定义订单
我有一个已映射的表,但是在编译后,可以在该表中添加或删除其他列.我正在尝试提出一个linq查询,该查询将考虑这些新列.在这种情况下,我想按那些动态列之一进行排序.这就是我到目前为止所拥有的.
I have a table that's mapped, but after compile additional columns can be added or removed from the table. I'm trying to come up with a linq query that will take those new columns into account. In this scenario, I want to order by one of those dynamic columns. This is what I have so far.
var queryableData = dc.wf_task_ext_attributes.AsQueryable();
ParameterExpression pe = Expression.Parameter(typeof(DateTime), "ExtValue105");
// The next line is where it fails
MethodCallExpression orderByCallExpression = Expression.Call(
typeof(Queryable),
"OrderBy",
new Type[] { queryableData.ElementType, queryableData.ElementType },
queryableData.Expression,
Expression.Lambda<Func<DateTime, DateTime>>(pe, new ParameterExpression[] { pe }));
IQueryable<string> results = queryableData.Provider.CreateQuery<string>
(orderByCallExpression);
失败,并显示以下消息:
It's failing with the following message:
类型为'System.Linq.Queryable'的通用方法'OrderBy'与提供的类型实参和实参不兼容.如果该方法是非泛型的,则不应该提供任何类型的参数.
No generic method 'OrderBy' 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.
我在做什么错了?
您的代码尝试创建类似Queryable.OrderBy(queryableData.Expression, ExtValue105 => ExtValue105)
的代码.我不知道您为什么希望它能起作用.
Your code tries to create something like Queryable.OrderBy(queryableData.Expression, ExtValue105 => ExtValue105)
. I have no idea why would you expect that to work.
如果我正确理解了您的问题,则需要动态创建一个类似attribute => attribute.ExtValue105
的表达式,然后可以使用它来调用OrderBy()
.
If I understand your question correctly, you need to dynamically create an expression like attribute => attribute.ExtValue105
and then you can use that to call OrderBy()
.
代码可能看起来像这样(假设queryableData
是IQueryable<Attribute>
):
The code could look something like this (assuming queryableData
is IQueryable<Attribute>
):
var parameter = Expression.Parameter(typeof(Attribute), "attribute");
var property = Expression.Property(parameter, "ExtValue105");
var lambda = Expression.Lambda(property, parameter);
IQueryable<Attribute> results =
Queryable.OrderBy(queryableData, (dynamic)lambda);
您可以手动使用queryableData.Provider.CreateQuery()
来避免dynamic
调用,但这会更加复杂.
You could use queryableData.Provider.CreateQuery()
manually to avoid the dynamic
call, but that would be more complicated.