英文:
Can I disable/enable lazy loading selectively in EF Core?
问题
在 Entity Framework 中,显然可以禁用延迟加载单个属性:
若要关闭特定属性的延迟加载,请不要将其设置为虚拟属性。
但在 EF Core 中,我会遇到以下异常:
InvalidOperationException: 属性 'DBO.Property' 不是虚拟的。'UseChangeTrackingProxies' 要求所有实体类型都必须是公共的、未密封的,具有虚拟属性,并具有公共或受保护的构造函数。'UseLazyLoadingProxies' 只要求导航属性是虚拟的。
(此异常在我的 DbContext 派生构造函数中设置 ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTrackingWithIdentityResolution
时抛出。)
我正在使用此错误中提到的第二种方法(使用 Microsoft.EntityFrameworkCore.Proxies 包):
// 在我的从 DbContext 派生的类中
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseLazyLoadingProxies(true);
}
我可以在 EF Core 中关闭单个属性的延迟加载吗?
英文:
In Entity Framework it was is evidently possible to disable lazy loading for individual properties:
> To turn off lazy loading for a particular property, do not make it virtual.
But in EF Core I get this exception:
> InvalidOperationException: Property 'DBO.Property' is not virtual. 'UseChangeTrackingProxies' requires all entity types to be public, unsealed, have virtual properties, and have a public or protected constructor. 'UseLazyLoadingProxies' requires only the navigation properties be virtual.
(This is thrown when setting ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTrackingWithIdentityResolution
in my DbContext-derived constructor.)
I'm using the second method mentioned in this error (with the Microsoft.EntityFrameworkCore.Proxies package):
// in my class derived from DbContext
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseLazyLoadingProxies(true);
}
Can I turn off lazy loading for a single property in EF Core?
答案1
得分: 1
你可以尝试按照这篇文章操作:
https://learn.microsoft.com/en-us/ef/core/querying/related-data/lazy
无代理的延迟加载
看起来可以使用ILazyLoader来为特定属性定义。
英文:
You can try follow this article:
https://learn.microsoft.com/en-us/ef/core/querying/related-data/lazy
> Lazy loading without proxies
It seems like it can be defined for specific properties with ILazyLoader.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论