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


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

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

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

如果MaxLength特性,应用在其他类型的属性上就报错,例如下面的图中例子:
enter description here
enter description here

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 here

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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM