EF Core 6对象不加载父实体或子实体。

huangapple go评论59阅读模式
英文:

EF Core 6 objects dont load parent or child entities

问题

根据这篇文章

据我所了解,如果您的对象按照以下示例定义,EF Core 6会自动映射对象关系:

public class Device
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int DeviceGroupId { get; set; }

    public DeviceGroup DeviceGroup { get; set; }
}

public class DeviceGroup
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<Device> Devices { get; set;}
}

然而,对我来说没有起作用。

在我的数据库表中:

  • Device.IdDeviceGroup.Id 是主键(整数,自增)
  • Device.DeviceGroupId 是一个整数,其外键在 Device.DeviceGroupIdDeviceGroup.Id 之间定义

我了解您也可以通过重写 DbContext 的 OnModelCreating 方法来显式指定这些关系,但我更愿意了解为什么上面的实现不起作用。

英文:

Referring to this article:

From what I understand, EF Core 6 object relationships are automagically mapped if your objects are defined per the example below:

public class Device
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int DeviceGroupId { get; set; }

    public DeviceGroup DeviceGroup { get; set; }
}

public class DeviceGroup
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection&lt;Device&gt; Devices { get; set;}
}

However, its not working for me.

In my DB tables:

  • Device.Id and DeviceGroup.Id are primary keys (integer, identity)
  • Device.DeviceGroupId is an integer with foreign key defined between Device.DeviceGroupId and DeviceGroup.Id

I understand you can also specify these relationships explicitly by override the OnModelCreating of the DbContext, but I'd prefer to understand why my implementation above isnt working.

答案1

得分: 0

EF Core默认提供延迟加载,如果您想要包含所有相关的实体,必须使用急加载,可以使用.Include()方法来实现,还可以使用.ThenInclude()进行链式操作。

英文:

EF Core by default provides LazyLoading, you have to use Eager Loading if you want to include all the related entities. That is done using .Include() method.
Which can also be chained using .ThenInclude().

huangapple
  • 本文由 发表于 2023年6月15日 19:23:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76481958.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定