Filtering non-generic DbSet with dynamically built Expression

dbset entity-framework expression-trees generics linq



As a façade for the DB context of Entity Framework, I have a class built. It was created to retain backward compatibility; instead of using EF entities, it resembles a class with the same public interface but utilizes DTOs.


I have the following method in the class mentioned above. View the code here:

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. As a consequence, I must accept an expression utilizing DTOs as the In input and return an IQueryable where T: BaseDto.
  2. I need to use EF entities as the In parameter to change the input predicate to the same predicate.
  3. I need to use a dynamically constructed Expression to filter non-generic EF DbSet (predicate)

major query

Is it feasible to use a dynamically generated expression to filter non-generic EF DBSet? (predicate)

If I need to use another method, kindly provide some glue or other information.

1/31/2017 12:34:20 AM

Popular Answer

The issue has been resolved. The answer was fairly simple. in place of

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

I'm a writer.

var query = dbContext

where the FindBy() method's input argument is predicate.

This code will properly compile, but more importantly, EF will construct an efficient query to the database that includes a Where() clause in the query body, preventing the need for the whole set of records from the database 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