jeudi 22 juillet 2021

Lambda Expressions and Polymorphism (EF Core) how to design this? [duplicate]

Assume the following base class

public abstract class BaseAction : Entity
{
    public DateTime CreationTime { get; private set; }
    public DateTime? CancellationTime { get; set; }
    public abstract Expression<Func<BaseAction, bool>> GetIdentifierExpression();
}

and the following attempt at a derived class

public class DerivedAction : BaseAction
{
    public string Name { get; set; }

    public override Expression<Func<BaseAction, bool>> GetIdentifierExpression()
    {
        ParameterExpression parameterExpression = Expression.Parameter(typeof(DerivedAction));
        return
            Expression.Lambda<Func<DerivedAction, bool>>(
                Expression.AndAlso(
                    Expression.AndAlso(
                        Expression.Equal(Expression.Constant(null),
                            Expression.Property(parameterExpression, nameof(CancellationTime))
                        ),
                        Expression.Equal(Expression.Constant(null),
                            Expression.Property(parameterExpression, nameof(ExecutionTime))
                        )
                    ),
                    Expression.Equal(Expression.Constant(Name),
                        Expression.Property(parameterExpression, nameof(Name))
                    )
                ),
            parameterExpression
        );
    }
}

I want to find a way to have a more specific implementation of GetIdentifierExpression in the derived class but the above does not compile since there is no implicit conversion between Expression<Func<DerivedAction, bool>> and Expression<Func<BaseAction, bool>>

The method eventually would get called like so

bool CheckActionIsInDB(BaseAction action)
{
    using var context = contextFactory.CreateDbContext();
    var set = context.Set<BaseAction>();
    return set.Any(action.GetIdentifierExpression());
}

Any ideas how to achieve such polymorphism on a method that returns Expressions?

Aucun commentaire:

Enregistrer un commentaire