【发布时间】:2021-11-08 04:49:53
【问题描述】:
一个 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; }
}
CoreSubAccount 模型
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();
}
【问题讨论】:
-
您能否展示如何使用 EF 查询数据?如果您没有包含 CoreSubAccounts,那么它可能无法正常工作。
标签: asp.net-core entity-framework-core odata .net-5