.NET 5 API 与 Entity Framework 一对多关系不起作用

.NET 5 API with Entity Framework One to Many Relationship Not Working

一个 CoreMasterAccount 有很多 CoreSubAccount。两者有一个共同的 MasterAccountId。 CoreSubAccount 有它自己唯一的 SubAccountId。 API json 响应将显示 SubAccounts[] 但数组为空。我做了一些调试工作,发现这不是 JSONNewtonsoft 序列化的问题。没有返回任何 CoreSubAccounts。对此一筹莫展。

CoreMasterAccount 模型

public partial class CoreMasterAccount
{
    public CoreMasterAccount()
    {
        CoreInvoices = new HashSet<CoreInvoice>();
        CoreSubAccounts = new HashSet<CoreSubAccount>();
        TxnManualTransactions = new HashSet<TxnManualTransaction>();
    }
    [Key]
    public long MasterAccountId { get; set; }
    public string ForeignKey { get; set; }
    public string CustomerName { get; set; }

    public virtual ICollection<CoreInvoice> CoreInvoices { get; set; }
    public virtual ICollection<CoreSubAccount> CoreSubAccounts { get; set; }
    public virtual ICollection<TxnManualTransaction> TxnManualTransactions { get; set; }
}

核心子账户模型

public partial class CoreSubAccount
{
    public CoreSubAccount()
    {
        CoreCircuits = new HashSet<CoreCircuit>();
    }
    [Key]
    public int SubAccountId { get; set; }
    public long MasterAccountId { get; set; }
    public string Btn { get; set; }
    public string CustomerName { get; set; }
    
    public virtual CoreMasterAccount MasterAccount { get; set; }
    public virtual ICollection<CoreCircuit> CoreCircuits { get; set; }
}

DBContext OnModelCreating:

modelBuilder.Entity<CoreSubAccount>(entity =>
        {
            entity.HasKey(e => e.SubAccountId)
                .HasName("PK_SubAccounts");

            entity.ToTable("core_SubAccounts");

            entity.HasIndex(e => e.Btn, "IX_core_SubAccounts")
                .IsUnique();
            .
            .
            .
            entity.HasOne(d => d.MasterAccount)
                .WithMany(p => p.CoreSubAccounts)
                .HasForeignKey(d => d.MasterAccountId)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_core_SubAccounts_core_MasterAccounts")
                .IsRequired();
        });

JSON 回应

{
"@odata.context": "https://localhost:5001/odata/$metadata#CoreMasterAccounts(CoreSubAccounts())",
"value": [{
        "MasterAccountId": 1,
        "ForeignKey": "X5202",
        "CustomerName": "Nunya",
        "CoreSubAccounts": []
    }
]

}

编辑: CoreMasterAccount 控制器:

    public async Task<ActionResult<IEnumerable<CoreMasterAccount>>> GetCoreMasterAccounts()
    {
        return await _context.CoreMasterAccounts.ToListAsync();
    }

您在查询主帐户时可能没有包括 CoreSubAccounts。如果没有您用来查询 CoreMasterAccounts 的实际代码,我只能质疑 Include 是问题所在。尝试以这种方式编写获取 CoreMasterAccounts 的查询:

return dbContext.CoreMasterAccounts
.Include(e => e.CoreSubAccounts)
.ToList();