Build expression tree with generic class for EF Core

215 views Asked by At

I have a TPH architecture with the following hierarchy:

abstract class Task
{
   public int A { get; set; }
}

abstract class DocumentTask
{
   public virtual Document Doc { get;set; }
   public int B { get; set; }
}

class DocumentTask<TDocument> : DocumentTask
   where TDocument : Document, new()
{
   public override TDocument Doc { get; set; }
}

/* Some classes are inherited from DocumentTask<TDocument> */

class SignTask<TDocument> : DocumentTask<TDocument>
  where TDocument : Document, new()
{
   public int C { get;set; }
}

And I need to get all SignTask from the database with the specified C. But as I don't have non-generic SignTask, I cannot do something like that db.Where(t => t is SignTask && ((SignTask)t).C == 5). That's why I decided to build an Expression tree directly and it works to get entities only of SignTask<> type:

var taskTypes = typeof(SignTask<>).Assembly
        .GetTypes()
        .Where(t => 
            (t?.BaseType?.IsGenericType ?? false) 
            && t?.BaseType?.GetGenericTypeDefinition() == typeof(SignTask<>)).ToList();

var parameter = Expression.Parameter(typeof(Task), "e");
    var body = taskTypes.Select(type => Expression.TypeIs(parameter, type))
        .Aggregate<Expression>(Expression.OrElse);

var predicate = Expression.Lambda<Func<Task, bool>>(body, parameter);

var tasks = await _dbContext
        .Tasks
        .Where(predicate)
        .ToArrayAsync();

But I cannot filter it by the C property, as I cannot build Expression.Parameter for generic type without a specified generic argument. Is there a way to implement this query?

1

There are 1 answers

0
Svyatoslav Danyliv On

If DocumentTask is derived from Task, you can do the following:

var parameter = Expression.Parameter(typeof(Task), "e");
var valueExpr = Expression.Constant(c);
var body = taskTypes.Select(type => Expression.AndAlso(Expression.TypeIs(parameter, type),
    Expression.Equal(
      Expression.Property(Expression.Convert(parameter, type), nameof(SignTask<Document>.C)),
      valueExpr)))
  .Aggregate<Expression>(Expression.OrElse);

var predicate = Expression.Lambda<Func<Task, bool>>(body, parameter);