EF6 - 包含列表<func <t,object =“”>&gt;的对象

时间:2016-10-23 12:21:03

标签: c# linq include entity-framework-6 entity

我希望Include个对象通过“Funcs”查询,而不是按字符串查询。这次我这样做(pagedListFunc.IncludesList<string>):

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

我想使用此列表:

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

当我尝试使用pagedListFunc.IncludeFuncs时(事实上,它位于列表上方: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
}

如何正确使用IncludeFuncs

1 个答案:

答案 0 :(得分:1)

参数的正确类型为Expression<Func<T, object>>,这意味着您的IncludeFuncs必须是docs中所述的List<Expression<Func<Dicts, object>>()类型。

作为旁注,不是使用List,而是params关键字和简单数组的一个很好的用例。使用该方法,您可以在调用方法时指定可变数量的参数。

这看起来像这样(伪代码):

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

用法:

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