【问题标题】:Dotnet 5.0 referencing child entity without includeDotnet 5.0 引用没有包含的子实体
【发布时间】: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


    【解决方案1】:

    上下文缓存结果,当你得到所有的 LegalPerson 实体时,EF 知道 LegalPersonParent ID 的 LegalPerson 是什么,所以放在那里 当你只得到一个 LegalPerson 时,如果 LegalPersonParentID 与所选的 LegalPerson 不同,EF 不知道 LegalPersonParent ID 的 LegalPerson 是什么

    如果您在获得所有具有相同上下文的 LegalPerson 之前获得所有 ActivityBranch,您会看到所有 ActivityBranch 也已解决

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多