英文:
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.Id和DeviceGroup.Id是主键(整数,自增)Device.DeviceGroupId是一个整数,其外键在Device.DeviceGroupId和DeviceGroup.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<Device> Devices { get; set;}
}
However, its not working for me.
In my DB tables:
Device.IdandDeviceGroup.Idare primary keys (integer, identity)Device.DeviceGroupIdis an integer with foreign key defined betweenDevice.DeviceGroupIdandDeviceGroup.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().
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论