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

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

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

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

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):
enter description hereapp

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

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

相关文章
相关标签/搜索