ciao seguo la guida in https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/how-to-use-expression-trees-to-build-dynamic- query per creare filtri e ordinamenti nella mia classe di relazione, ho bisogno di filtrare e ordinare usando la colonna "Canale" dei bambini
questa è la mia classe base
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; }
}
e questa è la Classe Meter
public class Meter : EviModelBase
{
public MeterVendor Vendor { get; set; }
public string Model { get; set; }
public string SerialNumber { get; set; }
public string Channel { get; set; }
}
questo è il codice per filtrare e ordinare i dati:
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);
}
}
In realtà "whereCallExpression" sta funzionando e filtrando i dati che voglio senza errori, ma la logica di ordinamento genera un errore "nessun metodo generico 'OrderBy' sul tipo 'System.Linq.Queryable' è compatibile con gli argomenti e gli argomenti del tipo fornito ".
Come posso raggiungere questo obiettivo ?
Saluti
Ti manca il fatto che, in contrasto con Where
, il metodo OrderBy
ha 2 argomenti di tipo generico ( TSource
e TKey
). Quindi è necessario fornire entrambi quando si genera una chiamata:
var orderByCallExpression = Expression.Call(
typeof(Queryable),
method,
new Type[] { source.ElementType, orderByExpression.Body.Type }, // <--
whereCallExpression,
Expression.Quote(orderByExpression));