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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值