ef core给字段增加校验,比如字符长度限制、验证是否邮箱?

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; }

}
posted on 2025-03-27 20:28  一只小小的程序猿  阅读(27)  评论(0)    收藏  举报