How to replace the switch statement of an expression

I have some code redirection based on an enum value passed to it, which then does a database query (via EF)

switch(regtype)
{
    case RegType.Type1:
        return (Dc.ListPeople(n => n.RegistrationType1Id != null)
        .DefaultIfEmpty()
        .Max(n => n.RegistrationType1Id ) ?? 0) + 1;
    case RegType.Type2:
        return (Dc.ListPeople(n => n.RegistrationType2Id != null)
        .DefaultIfEmpty()
        .Max(n => n.RegistrationType2Id ) ?? 0) + 1;
...
}

      

Now the data model is what it is, let it look at it. RegistrationType_N_Id

is int?

, ListPeople

takes an argument Expression<Func<Person, bool>>

.

There are only 3 enum values, so it's not that bad, but even for mental exercise, I would like to know if I can replace this switch statement with something more fancy.

I thought about Dictionary<RegType, Expression<Func<something>>>

, but since the first use in the db predicate is different from the second in Max()

, I got a dead end.

+3


source to share


1 answer


You can create a separate method that will use the property selector as a parameter. Entity Framework cannot directly interact with delegates as it has to translate your code to SQL, so you need to deal with expression trees.

public int M(Expression<Func<Person, int?>> selector)
{
    var expr = Expression.NotEqual(selector.Body, Expression.Constant(null, typeof(object)));
    var lambda = Expression.Lambda<Func<Person, bool>>(expr, selector.Parameters);

    return (Dc.ListPeople(lambda)
    .DefaultIfEmpty()
    .Max(selector)) ?? 0) + 1;
}

      



Using:

switch(regtype)
{
    case RegType.Type1:
        return M(x => x.RegistrationType1Id);

      

+3


source







All Articles