.NET 5 Core Entity Framework 控制器 w/OData Return 带有子对象的子对象

.NET 5 Core Entity Framework Controller w/OData Return Child Object with a Child Object

CoreMasterAccount 有很多 CoreSubAccount。 CoreSubAccounts 有很多 CoreCircuits。

目前,https://localhost:5001/odata/CoreMasterAccounts?$top=2&$expand=CoreSubAccounts($expand=CoreCircuits) returns:

"value": [{
        "MasterAccountId": 1,
        "ForeignKey": "foreignkey1",
        "CustomerName": "Nunya",
        "CoreSubAccounts": [{
                "SubAccountId": 1,
                "MasterAccountId": 1,
                "Btn": "630-323-8400",
                "CustomerName": "Nunya1",
                "CoreCircuits": []
            }, {
                "SubAccountId": 2,
                "MasterAccountId": 1,
                "Btn": "630-920-1100",
                "CustomerName": "Nunya2",
                "CoreCircuits": []
            }, {
                "SubAccountId": 3,
                "MasterAccountId": 1,
                "Btn": "708-444-2100",
                "CustomerName": "Nunya3",
                "CoreCircuits": []
            },

我也希望填充 CoreCircuits。这是通过控制器发生的还是与模型有关? Fyi CoreCircuits 与 CoreSubAccounts 具有多对一关系,其结构与 CoreSubAccounts 与 CoreMasterAccounts 具有多对一关系的结构相同,工作正常。

CoreMasterAccount 控制器:

public async Task<ActionResult<IEnumerable<CoreSubAccount>>> GetCoreSubAccounts()
    {
        return await _context.CoreSubAccounts
           .Include(e => e.CoreCircuits)
           .ToListAsync();
    }


 public async Task<ActionResult<IEnumerable<CoreMasterAccount>>> GetCoreMasterAccounts()
    {
        return await _context.CoreMasterAccounts
            .Include(e => e.CoreSubAccounts)
            .Include(e => e.CoreInvoices)
            .Include(e => e.TxnManualTransactions)
            .ToListAsync();
    }

核心子账户控制器:

public async Task<ActionResult<IEnumerable<CoreSubAccount>>> GetCoreSubAccounts()
    {
        return await _context.CoreSubAccounts
           .Include(e => e.CoreCircuits)
           .ToListAsync();
    }

像这样更改您的 GetCoreSubAccounts 代码:

public async Task<ActionResult<IEnumerable<CoreSubAccount>>> GetCoreSubAccounts()
    {
        return await _context.CoreSubAccounts
           .Include(e => e.CoreCircuits)
               .ThenInclude(e => e.CoreCircuits)
           .ToListAsync();
    }

您可以在此处找到更多信息和示例:https://entityframeworkcore.com/querying-data-include-theninclude