简体   繁体   English

EF Linq包含多个字符串

[英]EF Linq Include multiple strings

So I'm trying to retrieve (one or more) children of some entities using EF Linq. 因此,我尝试使用EF Linq检索(一个或多个)某些实体的子代。 The strange thing is that this isn't working: 奇怪的是,这不起作用:

public static class DbSetExtension
{
    public static IQueryable<T> Include<T>(this IDbSet<T> dbSet, params string[] paths) where T : class
    {
        foreach (var path in paths)
            dbSet.Include(path: path);

        return dbSet;
    }
}

//Usage: dbSet<Company>().Include(paths: nameof(Company.Projects))

In this case, every child is empty... But when I use this, it works: 在这种情况下,每个孩子都是空的...但是当我使用它时,它可以工作:

dbSet.Include("Projects");

Does anyone know why? 有人知道为什么吗? And what I could do to solve this? 我该怎么做才能解决这个问题?

Solution

public static IQueryable<T> Include<T>(this IQueryable<T> queryable, params string[] paths) where T : class
{
    foreach (var path in paths)
        queryable = queryable.Include(path: path);

    return queryable;
}

.Include doesn't actually change anything about dbSet . .Include实际上不会更改dbSet任何内容。 It returns a value, not modifies the object it's called on. 它返回一个值,而不修改它被调用的对象。

foreach(var path in paths)
{
    dbSet = dbSet.Include(path: path);
}

should work. 应该管用。

Well, by itself, this: 好吧,这本身就是:

dbSet.Include(path: path);

doesn't alter the state of the dbSet. 不会更改dbSet的状态。

So when you are returning, the include is not "included". 因此,当您返回时,包含不会被“包含”。

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

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