Staly Staly - 1 month ago 9
C# Question

EF6 - Include objects with List<Func<T, object>>

I want to

Include
objects to query by "Funcs", not by strings. This time I do it that way (
pagedListFunc.Includes
is
List<string>
):

foreach (var include in pagedListFunc.Includes)
{
query = query.Include(include);
}


I want to use this list:

IncludeFuncs = new List<Func<Dicts, object>>()
{
x => x.AspNetUsers,
x => x.DictDomains
};


When I try to use pagedListFunc.IncludeFuncs (in fact, it's above list:
List<Func<T, object>>
):

foreach (var include in pagedListFunc.IncludeFuncs)
{
query = query.Include(x => include(x)); // doesn't work
// or
query = query.Include(include); // wrong parameter error
}


How to use
IncludeFuncs
properly?

Answer

The correct type for the parameter is Expression<Func<T, object>>, which means that your IncludeFuncs must be of type List<Expression<Func<Dicts, object>>() as stated in the docs.

As a sidenote, instead of using a List, this would be a nice use case for the params keyword and a simple array. With that approach, you could specify a variable number of arguments when calling the method.

This would look like this for example (pseudocode):

public Dicts GetById(int id, params Expression<Func<Dicts, object>>[] includeProps)
{
    ...
    foreach(var include in includeProps)
    {
        query = query.Include(include);
    }
    ...
}

Usage:

GetById(1, x => x.AspNetUsers, x => x.DictDomains);
Comments