N
N
NameOf Var2020-02-21 14:09:17
ASP.NET
NameOf Var, 2020-02-21 14:09:17

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();


But this code doesn't work for me. Crashes with an error:
'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.'


If you transfer expresses separately, then everything works. So I somehow combine these expressions incorrectly? What could be wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2020-02-21
@hax

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();
}

PS
But if you want to get confused about expresses, then here is a report for you

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question