1、在实体类的属性字段上面加数据注释
using System.ComponentModel.DataAnnotations;
public class User
{
public int Id { get; set; }
// 必须字段,且长度限制 2-50 字符
[Required]
[StringLength(50, MinimumLength = 2)]
public string Name { get; set; }
// 最大长度 100 字符(可空字段)
[StringLength(100)]
public string Email { get; set; }
}
2、使用 fluent API 配置模型
官方文档:https://learn.microsoft.com/zh-cn/ef/core/modeling/
using Microsoft.EntityFrameworkCore;
namespace EFModeling.EntityProperties.FluentAPI.Required;
internal class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
#region Required
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.IsRequired();
}
#endregion
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}