【发布时间】:2021-10-18 21:03:42
【问题描述】:
我在一个使用 dotnet 5 的 dotnet 项目中。这个项目不是代码优先,我正在使用“dotnet ef dbcontext scaffold”创建实体关系,我遇到了这个问题:
我有一个指向自身的实体:LegalPerson -> LegalPersonParent
public partial class LegalPerson
{
[Key]
[Column("id")]
public long Id { get; set; }
[Column("idPessoa")]
public long PersonId { get; set; }
[Column("idPessoaJuridicaPai")]
public long? LegalPersonParentId { get; set; }
[Column("idRamoDeAtividade")]
public long? ActivityBranchId { get; set; }
[ForeignKey(nameof(LegalPersonParentId))]
public virtual LegalPerson LegalPersonParent { get; set; }
[ForeignKey(nameof(PersonId))]
public virtual Person Person { get; set; }
[ForeignKey(nameof(ActivityBranchId))]
public virtual ActivityBranch ActivityBranch { get; set; }
}
但是当我得到所有 LegalPersons 时,我也得到了 LegalPersonParent。
context.LegalPersons.ToList();
返回:
[
{
"id": 1365,
"personId": 1,
"legalPersonParentId": 1367,
"activityBranchId": 1,
"legalPersonParent": {
"id": 1367,
"personId": 6,
"legalPersonParentId": null,
"activityBranchId": null,
"legalPersonParent": null,
"person": null,
"activityBranch": null
},
"person": null,
"activityBranch": null
},
... more data
]
我想要的是仅在添加 Include 方法时添加 LegalPersonParent,例如:
context.LegalPersons.Include(legalPerson => legalPerson.LegalPersonParent).ToList();
还有更多有趣的事情正在发生。返回 context.LegalPersons.ToList();以前,ActivityBranch 和 Person 工作正常,没有得到实体,只有参考 id -> activityBranchId 和 personId
发生的另一件有趣的事情是,当我搜索一个 LegalPerson 时,它没有得到 LegalPersonParent:
_context.LegalPersons.FirstOrDefault(legalPerson => legalPerson.Id == id);
返回:
{
"id": 1365,
"personId": 1,
"legalPersonParentId": 1367,
"activityBranchId": 1,
"legalPersonParent": null,
"person": null,
"activityBranch": null
}
DbContext:
modelBuilder.Entity<LegalPerson>(entity =>
{
entity.HasIndex(e => e.PersonId, "IDX_PessoaJuridica_idPessoa")
.HasFillFactor((byte)70);
});
【问题讨论】:
标签: asp.net entity-framework .net-core