IsRequired() 是 EF Core 中配置数据库列“非空”约束的 Fluent API 方法,用于 OnModelCreating() 中,需与属性类型匹配并推荐结合 C# 可空引用类型使用。

在 EF Core 中,IsRequired() 是用来配置实体属性是否为数据库列的“非空”(NOT NULL)约束的方法,它属于 Fluent API 配置方式,通常在 OnModelCreating() 中使用。它不直接控制 C# 属性是否可空(那是类型系统的事),而是告诉 EF Core:这个字段在数据库中必须有值,插入或更新时不能为 NULL。
对一个属性调用 IsRequired(),EF Core 会在迁移生成的 SQL 中为其加上 NOT NULL 约束(前提是该属性本身是可空类型,否则默认就是非空)。
int、DateTime)默认就是非空,无需显式调用 IsRequired(),EF Core 也会生成 NOT NULL 列string、自定义类)默认是可空的,若想强制非空,就必须用 IsRequired()
int?、DateTime?)默认是可空列,若想让它变非空,需配合 IsRequired() + 类型调整(比如改成 int)假设你有一个 Product 实体:
public class Product
{
public int Id { get; set; }
public string Name { get; set; } // string 默认可空
public decimal Price { get; set; } // decimal 是值类型,默认非空
public DateTime? CreatedAt { get; set; } // 可空 DateTime
}在 DbContext.OnModelCreating() 中这样配置:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.Property(p => p.Name)
.IsRequired(); // Name 字段在数据库中变成 NOT NULL
<pre class="brush:php;toolbar:false;">modelBuilder.Entity<Product>()
.Property(p => p.CreatedAt)
.IsRequired(); // ❌ 错误!CreatedAt 是 DateTime?,不能直接设为 Required}
上面最后一行会报错,因为类型和约束冲突。正确做法是:要么改属性类型为 DateTime,要么不用 IsRequired();如果真要数据库非空且允许代码里为 null,可以用 IsRequired(true)(EF Core 7+ 支持“required without backing field”语义,但实际仍建议类型一致)。
如果你启用了 C# 的可空引用类型(#nullable enable),推荐写法是:
string),再加 IsRequired()(双重保障)string?),不加 IsRequired()
这样编译器警告 + 数据库约束一起守住空值边界,减少运行时异常。
不想用 Fluent API?也可以用特性:
public class Product
{
public int Id { get; set; }
<pre class="brush:php;toolbar:false;">[Required] // System.ComponentModel.DataAnnotations.RequiredAttribute
public string Name { get; set; }
public decimal Price { get; set; }}
注意:[Required] 在 EF Core 中也会让字段变为 NOT NULL,但它还会影响模型验证(比如 ASP.NET Core MVC 绑定时)。Fluent API 更专注数据映射,优先推荐。
基本上就这些。关键是记住:IsRequired() 是数据库约束配置,不是运行时校验;它和属性类型要匹配,配合可空引用类型一起用效果最好。
以上就是EF Core IsRequired()怎么用 EF Core设置字段为非空方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号