你好我按照https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/how-to-use-expression-trees-to-build-dynamic-queries中的指南在我的关系类中创建过滤和排序,我需要使用children列过滤和排序"频道"
这是我的基类
public class MeterTransaction : EviModelBase
{
public int TariffDuration { get; set; }
public decimal? TariffPackageKwh { get; set; }
public decimal? TariffPackagePrice { get; set; }
public decimal? TariffRatePerKwh { get; set; }
public decimal? TariffRateMinFee { get; set; }
// Meter CreditBalance after transaction
public decimal CreditBalance { get; set; }
public DateTimeOffset? CreditExpiration { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
public Meter Meter { get; set; }
}
这是Meter Class
public class Meter : EviModelBase
{
public MeterVendor Vendor { get; set; }
public string Model { get; set; }
public string SerialNumber { get; set; }
public string Channel { get; set; }
}
这是过滤和排序数据的代码:
public static IQueryable<T> OrderByNew<T>(this IQueryable<T> source, SortModel sortModel)
{
ParameterExpression p = Expression.Parameter(typeof(T), "p");
// Construct the nested properties
string[] nestedProps = sortModel.ColId.Split('.');
Expression mbr = p;
for (int i = 0; i < nestedProps.Length; i++)
mbr = Expression.PropertyOrField(mbr, nestedProps[i]);
LambdaExpression pred = Expression.Lambda(
Expression.Equal(
mbr,
Expression.Constant("EVI0000101")
),
p
);
var method = string.Equals(sortModel.Sort, "desc", StringComparison.OrdinalIgnoreCase) ?
"OrderByDescending" :
"OrderBy";
var whereCallExpression = Expression.Call(typeof(Queryable), "where", new Type[] { source.ElementType }, source.Expression, pred);
var orderByExpression = Expression.Lambda(mbr, p);
MethodCallExpression orderByCallExpression = Expression.Call(
typeof(Queryable),
method,
new Type[] { source.ElementType},
whereCallExpression,
Expression.Quote(orderByExpression));
// ***** End OrderBy *****
return source.Provider.CreateQuery<T>(orderByCallExpression);
}
}
实际上&#34; whereCallExpression&#34;正在进行罚款并过滤我想要的数据而没有错误,但排序逻辑会给出错误&#34;没有通用的方法&#39; OrderBy&#39; on type&#39; System.Linq.Queryable&#39;与提供的类型参数和参数兼容。&#34;
我怎样才能做到这一点?
问候
答案 0 :(得分:2)
您错过了与Where
相比较的事实,OrderBy
方法有2个泛型类型参数(TSource
和TKey
)。因此,您需要在生成呼叫时提供它们:
var orderByCallExpression = Expression.Call(
typeof(Queryable),
method,
new Type[] { source.ElementType, orderByExpression.Body.Type }, // <--
whereCallExpression,
Expression.Quote(orderByExpression));