gpt4 book ai didi

entity-framework - Entity Framework 7 Fluent API 无法识别 IsOptional()

转载 作者:行者123 更新时间:2023-12-03 07:32:28 31 4
gpt4 key购买 nike

我目前正在使用 Entity Framework 7(之前使用 EF 6)在 Asp.Net 5 项目中设置数据库,当我想让某些列可为空时,我会使用:

modelBuilder.Entity<Article>().Property(t => t.ArticleDateModified).IsOptional();

但似乎 IsOptional 不再是 EF7 的一部分,我想知道如何使用 EF7 实现同样的事情?

编辑:马克的答案确实是正确的,首先我认为它有效,因为我发现了类似 IsOptional:

builder.Entity<Article>().Property(t => t.ArticleDateModified).IsRequired(false);

但是当我在没有它的情况下运行一些测试后,它将数据库列设置为可为空,因为我在域模型中将其标记为可为空:

public DateTime? ArticleDateModified { get; set; }

还值得注意的是,当我将 DateTime 设置为不可空并使用 IsRequired(false) 时,出现以下错误:

The property 'ArticleDateModified' on entity type 'Article' cannot be marked as nullable/optional because the type of the property is 'DateTime' which is not a nullable type. Any property can be marked as non-nullable/required, but only properties of nullable types and which are not part of primary key can be marked as nullable/optional.

所以,我想知道如果要使数据库列可以为空我所要做的就是使其在我的域类中可以为空,那么这里的 IsRequired(false) 有什么用?

最佳答案

基于此 documentation page 中的注释,看来对以声明方式执行此操作的支持已被取消。也就是说:

A property whose CLR type cannot contain null cannot be configured as optional. The property will always be considered required by Entity Framework.

从 GitHub 上托管的项目的设计讨论中可以看出这是故意的,specifically :

That is, a property marked as nullable supports null values, while a property marked as non-nullable must never contain null values. It follows from this that marking a property which is of a non-nullable CLR type as allowing nulls will not be allowed. This is different from the EF6 behavior where this is allowed. [emphasis added]

<小时/>

结果是,在 EF7 中,NULL 列严格意味着可为 null 的映射属性。如果您的属性可为空,则关联列必须为 NULL,除非您使用 IsRequired 标记或配置它。

<小时/>

对 OP 编辑​​的响应

这很有趣,我最初并没有看到有关 IsRequired(bool) API 的文档。我在某个六月发现了一个关于它的讨论点meeting notes声明这相当于 EF6 的 IsOptional():

.IsOptional() - We'll provide this functionality via calling Required(false)
.IsRequired() - Provide Required() with the same functionality

尽管这是最初的意图,但撤销支持的设计决定是从 10 月份开始的。 (每次更新)尝试在不可为 null 的属性上设置 IsRequired(false) 会导致运行时错误,而不是被完全删除。

虽然现在是多余的,但在不破坏有效代码的情况下无法删除 API:它不是使用单独的 IsRequired(bool)IsRequired() 定义实现的,而是使用单个 IsRequired(bool required = true)。如果它被删除并替换为无参数版本,这将是一个重大更改。

关于entity-framework - Entity Framework 7 Fluent API 无法识别 IsOptional(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34408790/

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