I have a problem to generate dynamic func for using in an EF Core query.
This is the func generator
public static Expression<Func<TEntity, bool>> WhereFunc<TEntity>(this string propertyName,
object? propertyValue)
where TEntity : class, IEntity
{
var info = typeof(TEntity).GetProperty(propertyName);
var parameter = Expression.Parameter(typeof(TEntity), $"{nameof(TEntity).Substring(0,
2)}");
var property = Expression.Property(parameter, propertyName);
var value = Expression.Constant(propertyValue);
var clause = Expression.Equal(property, Expression.Constant(propertyValue));
return Expression.Lambda<Func<TEntity, bool>>(clause, parameter);
}
This is dynamic query generator for all properties need
public static IQueryable<TEntity> SetWhere<TEntity, TSearch>(this IEnumerable<TEntity>
entities, IEnumerable<PropertyInfo> fields, TSearch entity)
where TEntity : class, IEntity
where TSearch : class, ISearchEntity
{
var query = entities.AsQueryable();
if (fields != null && fields.Any())
foreach (var item in fields)
query = query.Where(EntityFuncs.WhereFunc<TEntity>(item.Name, item.GetValue(entity)));
return query;
}
This is my code to use this:
var query = Entities
.Skip(filter.Total)
.Take(filter.More)
.AsQueryable();
query = query.SetWhere<TEntity, TSearchEntity>(properties, filter.Entity);
For string properties it works correctly.
But in example for nullable<int> properties I get this error:
The binary operator Equal is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32