gpt4 book ai didi

c# - EFCore - 如何从自动加载中排除拥有的对象?

转载 作者:行者123 更新时间:2023-12-03 15:36:14 28 4
gpt4 key购买 nike

我试图围绕 EF Cores 拥有的对象以及如何控制何时加载某些数据块。

基本上我有一堆旧的遗留表(一些有大约 150 列),并希望使用一个根实体和每个表的几个拥有的对象对它们进行建模,以实现更好的分割和捆绑某些功能。示例:有一个“文章”实体,其中包含基础表中最重要字段的约 20 个属性。该实体还包含一个 OwnedObject“StorageDetails”,其中包含十多个字段(以及与存储内容相关的所有功能)。

问题:我找不到一种方法来控制是否应立即加载拥有的对象。对于其中一些,我更愿意使用 Include() 显式加载它们...

public class Article : EntityBase
{
public string ArticleNumber { get;set; }

// Owned object, shares article number as key.
public StorageDetails StorageStuff { get; set; }

// An Entity from another table having a foreign key reference
public SomeOtherEntity OtherStuff { get; set; }
}

public class StorageDetails : OwnedObject<Article>
{
public Article Owner { get; set; }
}

// Somewhere during model creation ...
builder.OwnsOne(article => article.StorageStuff);

builder.HasOne(article => article.OtherStuff )
...

使用 OwnsOne 定义模型并加载文章会立即加载 StorageStuff。要加载其他东西,我必须在查询中使用 Inlcude() 它,这基本上是我想要为拥有的对象实现的目标。

那可能吗?如果没有,您还能指点什么其他方法?

最佳答案

更新:我不是完全正确 - 拥有实体类型的隐式预加载实际上是默认设置,可以通过 SetIsEagerLoaded 更改元数据 API(EF Core 3.0+)

modelBuilder.Entity<Article>().OwnsOne(e => e.SorageStuff)
.Metadata.PrincipalToDependent?.SetIsEagerLoaded(false);
这允许通过 Include 加载它们/ ThenInclude .但由于 EF Core 实现细节,拥有的实体类型不能使用显式/延迟加载。尝试这样做会导致运行时异常。所以我在原始答案中的建议仍然适用。
原文:
对于拥有的类型 - 这是不可能的(当前),因为这种行为是“设计使然”。并记录在 Querying owned types 中EF Core 文档的部分:

When querying the owner the owned types will be included by default. It is not necessary to use the Include method, even if the owned types are stored in a separate table.


说“默认”有点含糊,但您可以放心地将其读为“始终”,因为没有选项或 Exclude方法。

由于目前控制加载相关数据的唯一方法是将导航属性设置为真实实体,因此将您想要控制的类型设为“真实实体”,即不要将它们标记为拥有,定义显式或影子 PK,并将这些映射“实体”与 Table Splitting :

It is now possible to map two or more entity types to the same table where the primary key column(s) will be shared and each row will correspond to two or more entities.

To use table splitting an identifying relationship (where foreign key properties form the primary key) must be configured between all of the entity types sharing the table:

关于c# - EFCore - 如何从自动加载中排除拥有的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54041802/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com