gpt4 book ai didi

entity-framework-core - 如何禁用可选的依赖实体

转载 作者:行者123 更新时间:2023-12-02 01:55:22 24 4
gpt4 key购买 nike

我有以下两个实体使用 EF Core 中的拆分表选项引用一个表 - 这是一个非常简化的版本:

class Account
int Id
Settings Settings

class Settings
int AccountId (maps to Id)
string PropertyX

来自documentation :

If all of the columns used by a dependent entity are NULL in thedatabase, then no instance for it will be created when queried. Thisallows modeling an optional dependent entity, where the relationshipproperty on the principal would be null. Note that this would alsohappen if all of the dependent's properties are optional and set tonull, which might not be expected.

是否可以禁用此行为?我有多个列,其中有很多默认为空的分组行为。

现在默认情况下不会创建实体(设置)。这意味着我必须到处进行空检查。我宁愿使用所有属性的空值创 build 置。

如果我自己在父实体(帐户)的构造函数中创建实例,则似乎不会跟踪更改,因为我猜 EF Core 不知道该类。

有什么解决办法吗?

最佳答案

遗憾的是,此功能在 EF Core 3 中不可用。

EF Core 5.0 中添加了所谓的必需依赖项 - Required 1:1 dependents :

In EF Core 3.1, the dependent end of a one-to-one relationship was always considered optional. This was most apparent when using owned entities, as all the owned entity's column were created as nullable in the database, even if they were configured as required in the model.

In EF Core 5.0, a navigation to an owned entity can be configured as a required dependent

以上只是“新增功能”部分中该功能的公告。事实上它可以用于任何一对一的关系,正如官方提到的One-to-one文档部分:

The dependent side is considered optional by default, but can be configured as required. However EF will not validate whether a dependent entity was provided, so this configuration will only make a difference when the database mapping allows it to be enforced. A common scenario for this are reference owned types that use table splitting by default

要根据需要配置依赖项,您必须将 Navigation Fluent API(也在 5.0 中引入)与 IsRequired 结合使用:

modelBuilder.Entity<Account>()
.Navigation(e => e.Settings)
.IsRequired();

关于entity-framework-core - 如何禁用可选的依赖实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69669167/

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