I'm trying to implement filter to my IQueryable
which will checks if list of objects contains some element.
var ratings = repository.GetAll<Rating>()
.AsNoTracking()
.Select(e => new RatingGridDto()
{
Id = e.Id,
Sites = e.Locations.Select(x => x.Name).ToList(),
PurchaseOrderNumbers= e.PurchaseOrderNumbers//this is IEnumerable of string
});
OrderNumber
in db looks like this: "[12345]","[5432]","[18859]".
I was trying to implement it in below way but nothing works... any linq expression and below implementation of own Expression throws error that it's not translatable to SQL.
Where is the problem and how I can resolve it?
ratings = ratings.Where(e => e.PurchaseOrderNumbers.AsQueryable().Any(pon => pon.Contains(purchaseOrderFilter)));
ratings = ratings.Where(e => e.PurchaseOrderNumbers.Where(pon => pon.Contains(purchaseOrderFilter)).Any());
ratings = ratings.Where(e => e.PurchaseOrderNumbers.Contains("222"));
ratings = ratings.Where(e => e.PurchaseOrderNumbers.Any(pon => pon == "234234"));
ratings = ratings.Where(e => e.Sites.Any(s => s.Contains("a"))); WORKS
ratings = ratings.Where(e => e.PurchaseOrderNumbers.Any(pon => pon.Contains("a")));
public static IQueryable<T> OwnWhereIsContainedBy<T, K>(IQueryable<T> source, K elementToContain, string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
{
throw new ArgumentException("Property name cannot be null or empty.", nameof(propertyName));
}
ParameterExpression parameter = Expression.Parameter(typeof(T));
MemberExpression property = Expression.Property(parameter, propertyName);
ConstantExpression element = Expression.Constant(elementToContain);
MethodInfo containsMethod = typeof(Enumerable).GetMethods()
.Where(m => m.Name == "Contains" && m.GetParameters().Length == 2)
.Single()
.MakeGenericMethod(typeof(K));
MethodCallExpression containsCall = Expression.Call(containsMethod, property, element);
Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(containsCall, parameter);
return source.Where(lambda);
}