【发布时间】:2019-08-26 19:44:29
【问题描述】:
我使用的是 EF Core 2.2.6(数据库优先),似乎只是启用延迟加载让我无法急切加载。启用延迟加载是否会排除在任何容量下使用急切加载?
namespace Example.Models
{
public class Lead
{
public int Id { get; set; }
public LeadOrganization LeadOrganization { get; set; }
public Lead(ExampleContext.Data.Lead dbLead)
{
Id = dbLead.Id;
LeadOrganization = new LeadOrganization(dbLead.LeadOrganization);
}
public static Lead GetLead(int id)
{
using (var db = new ExampleContext())
{
var dbLead = db.Leads
.Include(l => l.LeadOrganization)
.ThenInclude(lo => lo.LeadOrganizationAddresses)
.ThenInclude(loa => loa.AddressType)
.FirstOrDefault(l => l.Id== id);
return new Lead(dbLead);
}
}
}
}
namespace Example.Models
{
public class LeadOrganization
{
public IEnumerable<LeadOrganizationAddress> Addresses { get; set; }
public LeadOrganization(ExampleContext.Data.LeadOrganization dbLeadOrganization)
{
Addresses = dbLeadOrganization.LeadOrganizationAddresses.Select(loa => new LeadOrganizationAddress(loa));
}
}
}
namespace Example.Models
{
public class LeadOrganizationAddress
{
public AddressType AddressType { get; set; }
public LeadOrganizationAddress(ExampleContext.Data.LeadOrganizationAddress dbLeadOrganizationAddress)
{
AddressType = new AddressType(dbLeadOrganizationAddress.AddressType);
}
}
}
namespace Example.Models
{
public class AddressType
{
public short Id { get; set; }
public AddressType(ExampleContext.Data.AddressType dbAddressType)
{
Id = dbAddressType.Id;
}
}
}
ExampleContext.Data 命名空间包含数据库中 EF 生成的部分类。 Lead、LeadOrganization、LeadOrganizationAddress 和 AddressType 是在属性方面基本上是 1:1 的类,但添加了静态方法(是的,这很奇怪,但这是我必须使用的)。
Lead 有一个 LeadOrganization,而 LeadOrganization 又具有至少一个 LeadOrganizationAddress,而 LeadOrganizationAddress 又具有 AddressType。
当GetLead 调用Lead 构造函数时,查询中的数据尚未加载,即使它应该是预先加载的。这会导致嵌套对象出现问题。当它最终到达LeadOrganizationAddress 构造函数时,DbContext 已被释放,因此无法延迟加载关联的AddressType。
我是否误解了急切加载的全部意义?我认为它会在初始查询时检索所有数据,然后让我将其传递给构造函数而不会出现问题。我不需要继续返回数据库并延迟加载任何内容。
如果您启用了延迟加载,您是否可以不急切加载?是否有其他解决方法,例如强制它加载任何代理实体?
【问题讨论】:
-
"lead.LeadOrganization 是一个代理,因为它实际上还没有检索到数据" 我认为这种状态不存在。该属性要么是
null(未加载),要么是已加载的实例(代理与否无关紧要)。 EF Core 不会创建假实例,并且代理类可能用于将相关数据延迟加载到您的示例中未显示的LeadOrganization实体。此外,不清楚您所说的“按预期”是什么意思,以及您在谈论嵌套实体的构造函数有什么问题。我认为最好提供minimal reproducible example。 -
我已经更新了我的帖子,以便更清楚地了解我正在尝试做什么以及我所看到的。
标签: c# entity-framework-core ef-core-2.2