Answer the question
In order to leave comments, you need to log in
How can two Expressions be combined into one to get data from Entity Framework Core?
Hey! I have two expressions with conditions that I want to combine into one expression and feed it to Entity Framework Core.
Expression<Func<Device, bool>> deviceTypeFilter = d => d.DeviceTypes == DeviceTypes.Camera;
Expression<Func<Device, bool>> geolocationFilter = d => d.Latitude == 23.2;
var finalCriteria = Expression.AndAlso(deviceTypeFilter.Body, geolocationFilter.Body);
var lambda = Expression.Lambda<Func<Device, bool>>(finalCriteria, Expression.Parameter(typeof(Device)));
IQueryable<Device> query = this.Entities;
query = lambda != null ? query.Where(lambda) : query;
return await query.AsNoTracking().ToListAsync();
'The LINQ expression 'DbSet
.Where(d => (int)d.DeviceTypes == 1 && d.Latitude == 23,2)' 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 either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'
Answer the question
In order to leave comments, you need to log in
If you simply add to your Where query for each expression, then this will just be a logical "AND". I usually do this.
Code example:
Task<Device[]> FilteredDevices(params Expression<Func<Device, bool>> filters)
{
IQueryable<Device> query = this.Entities;
foreach(var filter in filters)
{
query = query.Where(filter);
}
return query.AsNoTracking().ToArrayAsync();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question