I need to Filter Products by list of related Entities. for example, I have a table related to Product Table named InventoryPrice that has Price with the color Table and I wanna filter Table Product by List of Colors
I used PredicateBuilder for defining Or in Loop:
var PredicateI = PredicateBuilder.New<InventoryPriceModel>();
foreach (var Color in Filter.Color)
PredicateI = PredicateI.Or(i => i.colorId == Color);
Query = Query
.Include(i => i.InventoryPrice.Where(PredicateI))
.ThenInclude(i => i.color);
and had this exception:
"Expression of type 'System.Func
2[ClickStore.UseCases.InventoryPrice.Models.InventoryPriceModel,System.Boolean]' cannot be used for parameter of type 'System.Linq.Expressions.Expression
1[System.Func2[ClickStore.UseCases.InventoryPrice.Models.InventoryPriceModel,System.Boolean]]' of method 'System.Linq.IQueryable
1[ClickStore.UseCases.InventoryPrice.Models.InventoryPriceModel] Where[InventoryPriceModel](System.Linq.IQueryable1[ClickStore.UseCases.InventoryPrice.Models.InventoryPriceModel], System.Linq.Expressions.Expression
1[System.Func`2[ClickStore.UseCases.InventoryPrice.Models.InventoryPriceModel,System.Boolean]])' (Parameter 'arg1')"
I used List.Contains in Where:
Query = Query
.Include(i => i.InventoryPrice
.Where(i => Filter.Color.Contains(x => x == i.colorId)))
.ThenInclude(i => i.color);
and had this exception:
{"The LINQ expression 'x => x == EntityShaperExpression: \r\n ClickStore.UseCases.InventoryPrice.Models.InventoryPriceModel\r\n ValueBufferExpression: \r\n ProjectionBindingExpression: EmptyProjectionMember\r\n IsNullable: False\r\n.colorId' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information."}
I did some Searching to fixing it but still no answer
CodePudding user response:
You can do something like this with pure LINQ,
List<YourColorEntity> colorList = ..... //Your color list
var yourQuery = Query
.Include(/*your related entities*/)
.Where(i => colorlist
.Any(c => c.colorId.Equals(i.colorId)));
And, in your List.Contains
query, you are missing the closing parenthesis after Include
.
CodePudding user response:
You should be able to fix this by using AsQueryable
on i.InventoryPrice
:
Query = Query
.Include(i => i.InventoryPrice.AsQueryable().Where(PredicateI))
.ThenInclude(i => i.color);
But for this particular case (based on provided code and some assumptions, cause there is not enough code provided to test it) simple Contains
should do the trick:
Query = Query
.Include(i => i.InventoryPrice.Where(ip => Filter.Color.Contains(ip.colorId)))
.ThenInclude(i => i.color);