9.9 翻译系列:数据注解特性之--MaxLength 【EF 6 Code-First系列】

原文连接:https://www.entityframeworktutorial.net/code-first/maxlength-minlength-dataannotations-attribute-in-code-first.aspxhtml

EF 6 Code-First系列文章目录:数据库

MaxLength特性指定了属性的值所容许的最大值,而后在数据库中就生成相应列的最大值。MaxLength特性能够应用于实体的String类型的属性和byte[]数组类型的属性上。数组

若是MaxLength特性,应用在其余类型的属性上就报错,例以下面的图中例子:
enter description here
enter description heremvc

using System.ComponentModel.DataAnnotations;
    
public class Student
{
    public int StudentID { get; set; }
    [MaxLength(50)]
    public string StudentName { get; set; }
        
}

上面代码例子中,MaxLength(50)应用在StudentName属性上,指定StudentName的属性值不能超过50个字符长度。
enter description hereapp

EF将会检查标识了MaxLength特性的属性值,若是长度超过了指定的长度,就会报错,EF6报错:System.Data.Entity.Validation.DbEntityValidationException ,EF Core报错:Microsoft.EntityFrameworkCore.DbUpdateException.asp.net

请注意:MaxLength特性,一样能够用在ASP.NET MVC中,用于验证属性的值,了解更多详情请看这篇文章: Implement Validations in ASP.NET MVC测试

相关文章
相关标签/搜索