Ho creato un generatore di espressioni generiche che crea un predicato basato sulla raccolta di condizioni. Trasmetto il predicato a un metodo generico nel repository. Penso che il generatore di espressioni funzioni bene e crei il predicato desiderato sebbene lo script SQL generato da Entity Framework non sia quello che mi aspettavo. Ho letto molte domande e articoli riguardanti la query dinamica o LinqKit e il generatore di espressioni per questo problema e il più rilevante è stato questo commento . Apprezzo davvero se tu potessi dare un'occhiata a quello che ho fatto e farmi sapere se ho fatto qualche errore?
Ecco il codice per la classe ExpressionBuilder:
public static class ExpressionBuilder
{
private static MethodInfo containsMethod = typeof(string).GetMethod("Contains");
private static MethodInfo startsWithMethod = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
private static MethodInfo endsWithMethod = typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) });
public static Expression<Func<T, bool>> GetExpression<T>(IList<ExpressionModel> filters)
{
if (filters == null)
return null;
IList<ExpressionModel> nullFreeCollection = filters.OfType<ExpressionModel>().ToList();
if (nullFreeCollection.Count == 0)
return null;
ParameterExpression param = Expression.Parameter(typeof(T), "item");
Expression exp = null;
if (nullFreeCollection.Count == 1)
exp = GetExpression<T>(param, nullFreeCollection[0]);
else if (nullFreeCollection.Count == 2)
exp = GetExpression<T>(param, nullFreeCollection[0], nullFreeCollection[1]);
else
{
while (nullFreeCollection.Count > 0)
{
var f1 = nullFreeCollection[0];
var f2 = nullFreeCollection[1];
if (exp == null)
exp = GetExpression<T>(param, nullFreeCollection[0], nullFreeCollection[1]);
else
exp = Expression.AndAlso(exp, GetExpression<T>(param, nullFreeCollection[0], nullFreeCollection[1]));
nullFreeCollection.Remove(f1);
nullFreeCollection.Remove(f2);
if (nullFreeCollection.Count == 1)
{
exp = Expression.AndAlso(exp, GetExpression<T>(param, nullFreeCollection[0]));
nullFreeCollection.RemoveAt(0);
}
}
}
return Expression.Lambda<Func<T, bool>>(exp, param);
}
private static Expression GetExpression<T>(ParameterExpression param, ExpressionModel filter)
{
MemberExpression member = Expression.Property(param, filter.PropertyName);
ConstantExpression constant = Expression.Constant(filter.Value);
switch (filter.Operator)
{
case ExpressionOperators.Equals:
return Expression.Equal(member, constant);
case ExpressionOperators.GreaterThan:
return Expression.GreaterThan(member, constant);
case ExpressionOperators.LessThan:
return Expression.LessThan(member, constant);
case ExpressionOperators.GreaterThanOrEqual:
return Expression.GreaterThanOrEqual(member, constant);
case ExpressionOperators.LessThanOrEqual:
return Expression.LessThanOrEqual(member, constant);
case ExpressionOperators.Contains:
return Expression.Call(member, containsMethod, constant);
case ExpressionOperators.StartsWith:
return Expression.Call(member, startsWithMethod, constant);
case ExpressionOperators.EndsWith:
return Expression.Call(member, endsWithMethod, constant);
}
return null;
}
private static BinaryExpression GetExpression<T>(ParameterExpression param, ExpressionModel filter1, ExpressionModel filter2)
{
Expression bin1 = GetExpression<T>(param, filter1);
Expression bin2 = GetExpression<T>(param, filter2);
return Expression.AndAlso(bin1, bin2);
}
public enum ExpressionOperators
{
Equals,
GreaterThan,
LessThan,
GreaterThanOrEqual,
LessThanOrEqual,
Contains,
StartsWith,
EndsWith
}
}
Ed ecco il metodo di repository generico:
public IEnumerable<TEntity> RetrieveCollectionAsync(Expression<Func<TEntity, bool>> predicate)
{
try
{
return DataContext.Set<TEntity>().Where(predicate);
}
catch (Exception ex)
{
Logger.Error(ex);
throw ex;
}
}
E script generato da Entity Framework per Sql (mi aspetto una query selezionata con alcune clausole where):
SELECT
CAST(NULL AS uniqueidentifier) AS [C1],
CAST(NULL AS uniqueidentifier) AS [C2],
CAST(NULL AS varchar(1)) AS [C3],
CAST(NULL AS uniqueidentifier) AS [C4],
CAST(NULL AS uniqueidentifier) AS [C5],
CAST(NULL AS uniqueidentifier) AS [C6],
CAST(NULL AS datetime2) AS [C7],
CAST(NULL AS datetime2) AS [C8],
CAST(NULL AS varchar(1)) AS [C9],
CAST(NULL AS uniqueidentifier) AS [C10],
CAST(NULL AS varchar(1)) AS [C11],
CAST(NULL AS uniqueidentifier) AS [C12],
CAST(NULL AS uniqueidentifier) AS [C13],
CAST(NULL AS uniqueidentifier) AS [C14],
CAST(NULL AS uniqueidentifier) AS [C15],
CAST(NULL AS datetime2) AS [C16],
CAST(NULL AS varchar(1)) AS [C17],
CAST(NULL AS datetime2) AS [C18],
CAST(NULL AS varchar(1)) AS [C19],
CAST(NULL AS tinyint) AS [C20]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
WHERE 1 = 0
sto usando
Aggiorna il modello per l'espressione:
public class ExpressionModel
{
public string PropertyName { get; set; }
public ExpressionOperators Operator { get; set; }
public object Value { get; set; }
}
Un'altra parte mancante è un mappatore generico che associa un determinato criterio di ricerca a un nuovo ExpressionModel che credo non sia rilevante per questo problema.
Come ho menzionato nei commenti, l'implementazione è troppo complicata.
Innanzitutto, questo metodo
private static BinaryExpression GetExpression<T>(ParameterExpression param, ExpressionModel filter1, ExpressionModel filter2)
e l'intera logica per il conteggio dei filtri, la rimozione degli oggetti elaborati, ecc. è ridondante. AND
condizioni possono essere facilmente incatenate in questo modo
((Condition1 AND Condition2) AND Condition3) AND Condition4 ...
Quindi basta rimuovere quella funzione.
Secondo, questa funzione
private static Expression GetExpression<T>(ParameterExpression param, ExpressionModel filter)
è mal chiamato e non ha bisogno di un T
generico perché non è usato all'interno.
Invece, cambia la firma in
private static Expression MakePredicate(ParameterExpression item, ExpressionModel filter)
{
// implementation (same as posted)
}
Infine, il metodo pubblico è semplice come quello:
public static Expression<Func<T, bool>> MakePredicate<T>(IEnumerable<ExpressionModel> filters)
{
if (filters == null) return null;
filters = filters.Where(filter => filter != null);
if (!filters.Any()) return null;
var item = Expression.Parameter(typeof(T), "item");
var body = filters.Select(filter => MakePredicate(item, filter)).Aggregate(Expression.AndAlso);
var predicate = Expression.Lambda<Func<T, bool>>(body, item);
return predicate;
}
PS E non dimenticare di fare il controllo null
nell'utilizzo:
// should not be called Async
public IEnumerable<TEntity> RetrieveCollectionAsync(Expression<Func<TEntity, bool>> predicate)
{
try
{
var query = DataContext.Set<TEntity>().AsQueryable();
if (predicate != null)
query = query.Where(predicate);
return query;
}
catch (Exception ex)
{
Logger.Error(ex);
throw ex; // should be: throw;
}
}