简体   繁体   English

如何在循环中链接多个DbSet.Include()?

[英]How to chain multiple DbSet.Include() in a loop?

How to include in loop? 如何包含在循环中? I want to specify related objects to include in query. 我想指定要包含在查询中的相关对象。

I have next function 我有下一个功能

    public IQueryable<TEntity> Include(Expression<Func<TEntity, object>>[] includes)
    {
        IQueryable<TEntity> result = null;

        //two includes are ok:
        //IQueryable<TEntity> result2 = null;
        //if (includes.Count() > 1)
        //{
            //result2 = dbset.Include(includes[0]).Include(includes[1]);
        //}

        //include in loop is not ok:
        foreach (var exp in includes)
        {
            result = dbset.Include(exp);
        }
        return result;
    }

If I uncomment commented code that result2 will be ok. 如果我取消注释代码,则result2可以。 But result is not ok. 但是结果不好。

Strange is that if I debug loop step by step, in every iteration checking result then result is ok. 奇怪的是,如果我一步一步调试循环,则在每次迭代检查结果中都可以。 But if I am not checking result step by step that include work just for last expresion. 但是,如果我没有一步一步地检查包括最后一次表达式工作在内的结果。

Do you have any idea why this is not working and how to fix? 您有什么想法为什么不起作用以及如何解决?


Edit: this is fix: 编辑:这是修复:

    result = dbset;
    foreach (var exp in includes)
    {
        result = result.Include(exp);
    }

The problem is that you keep overriding the value of result with the result of a single Include() call on the dbSet . 问题在于,您将使用dbSet上的单个Include()调用的结果来不断覆盖result的值。

You need to concatenate those calls as follows: 您需要按如下方式串联这些调用:

foreach (var exp in includes)
{
    result = result.Include(exp);
}

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

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