EF:动态构建IIncludeableQueryable

时间:2016-07-17 17:03:43

标签: c# asp.net entity-framework entity-framework-core

我有GET {id}以及包含关系的选项。

我想做这样的事情:

        var account = _context.Accounts.Where(a => a.AccountId == id);
        if (withActiveSubscription)
        {
            account = account.Include(a => a.ActiveSubscription);
            if (withCharges)
            {
                account = account.ThenInclude(s => s.Charges);
            }
        }

但我得到"无法解析符号'然后包括' " 。 我可以通过将其改为

来解决这个问题
            if (withCharges)
            {
                account = account.Include(a => a.ActiveSubscription).ThenInclude(s => s.Charges);
            }

但它看起来很糟糕,因为我复制account.Include(a => a.ActiveSubscription)。 那么,我应该如何编码呢? (我使用的是EF-core) 感谢

1 个答案:

答案 0 :(得分:1)

ThenInclude可用作.Include(...)返回的类型的扩展方法。该类型不仅仅是IQueryable<T>,而且通过分配给account,您可以消除编译时额外功能的知识。为了保留它,将它存储在一个额外的辅助变量中,该变量可以与account具有不同的类型:

var account = _context.Accounts.Where(a => a.AccountId == id);
if (withActiveSubscription)
{
    var accountAS = account.Include(a => a.ActiveSubscription);
    account = accountAS;

    if (withCharges)
    {
        var accountASC = accountAS.ThenInclude(s => s.Charges);
        account = accountASC;
    }
}