C# EF:构建IIIncludeableQueryable动态
我得到了{id},其中包含关系的选项 我想这样做:C# EF:构建IIIncludeableQueryable动态,c#,asp.net,entity-framework,entity-framework-core,C#,Asp.net,Entity Framework,Entity Framework Core,我得到了{id},其中包含关系的选项 我想这样做: var account = _context.Accounts.Where(a => a.AccountId == id); if (withActiveSubscription) { account = account.Include(a => a.ActiveSubscription); if (withCharges)
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);
}
}
但我得到“无法解析符号'ThenClude'”。
我可以把它改成
if (withCharges)
{
account = account.Include(a => a.ActiveSubscription).ThenInclude(s => s.Charges);
}
但这看起来很糟糕,因为我复制了帐户。Include(a=>a.ActiveSubscription)
。
那么,我应该如何编写代码呢?
(我正在使用EF core)
谢谢
,Include
作为扩展方法提供给返回的类型。Include(…)
。这种类型不仅仅是IQueryable
,通过分配给account
,您可以去掉额外功能的编译时知识。要保留它,请将其存储在额外的helper变量中,该变量可以具有与帐户不同的类型:
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;
}
}