简体   繁体   English

EF6-在清单中包含对象 <Func<T, object> &gt;

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

I want to Include objects to query by "Funcs", not by strings. 我想Include要通过“功能”而不是字符串查询的对象。 This time I do it that way ( pagedListFunc.Includes is List<string> ): 这次我这样做( pagedListFunc.IncludesList<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>> ): 当我尝试使用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
}

How to use IncludeFuncs properly? 如何正确使用IncludeFuncs

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 . 参数的正确类型为Expression<Func<T, object>> ,这意味着您的IncludeFuncs必须为docs中所述的List<Expression<Func<Dicts, object>>()

As a sidenote, instead of using a List , this would be a nice use case for the params keyword and a simple array. 作为附带说明,代替使用List ,这对于params关键字和一个简单的数组将是一个很好的用例。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM