Filtering non-generic DbSet with dynamically built Expression

dbset entity-framework expression-trees generics linq



I have a class implemented as a facade around Entity Framework DB context. It developed to maintain backward compatibility, it mimics class with same public interface, but uses DTOs instead of EF entities.


I have next method inside class described above. See code below:

public IQueryable<T> FindBy<T>(Expression<Func<T, Boolean>> predicate) where T : BaseDto {

//GetDestinationType takes source type of some declared mapping and returns destination type
var entityType = Mapping.Mapper.GetDestinationType(typeof (T));

var lambda = Expression.Lambda(predicate.Body, Expression.Parameter(entityType));

// dbContext declared as class field and initialized in constructor
var query = dbContext.Set(entityType).Where(lambda); // <-- Cannot use non-generic expression/lambda

return query.ProjectTo<T>(mapper.ConfigurationProvider); }
  1. I need to take Expression using DTOs as In parameter and return IQueryable where T : BaseDto as a result
  2. I need to convert input predicate to the same predicate using EF entities as In parameter
  3. I need to filter non-generic EF DbSet with help of dynamically created Expression (predicate)

Main question

Is it possible to filter non-generic EF DBSet with help of dynamically created Expression (predicate)

Please give me some glue or further directions if I need to use some other approach.

1/31/2017 12:34:20 AM

Popular Answer

Problem has been solved. Solution was quite obvious. Instead of

var query = dbContext.Set(entityType).Where(lambda);

I can write

var query = dbContext

where predicate is the input parameter of FindBy() method.

This code will be successfully compiled and, what is more important, EF will build optimal query to the Database which will include Where() clause in the query body, so it won't take full set of records from DB side.

1/31/2017 1:22:36 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow