原文链接:https://www.entityframeworktutorial.net/code-first/stringlength-dataannotations-attribute-in-code-first.aspx

StringLength特性可以应用于实体的string类型的属性上,它指定了属性的所允许的最大字符长度,然后对应在数据库中就生成相应长度的数据列(在SQL Server数据库中是,nvarchar类型)。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
using System.ComponentModel.DataAnnotations;

public class Student
{
    public int StudentID { get; set; }
    [StringLength(50)]
    public string StudentName { get; set; }
}

上面的例子中,我们将StringLength特性应用在StudentName属性上,所以EF将会在StudentName列,映射为nvarchar(50):
 9.10 翻译系列:EF数据注解特性之StringLength【EF 6 Code-First系列】 随笔

EF会验证StudentName的属性值的长度,如果大于50个字符长度,就报错:EF 6中:System.Data.Entity.Validation.DbEntityValidationException,EF Core中Microsoft.EntityFrameworkCore.DbUpdateException

请注意:StringLength特性,还可以用在ASP.NET MVC中,用来验证属性的值,了解更多,请看这篇文章:Implement Validations in ASP.NET MVC

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄