每天学一点,每天积累一点,进步就不止一点点!PS:好记性不如烂笔头,学会总结,学会思考~~~ ----要飞翔,必须靠自己!

灰太狼的梦想

好记性不如烂笔头,学会总结,学会思考~~~

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

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

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

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

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 here

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

posted @ 2019-04-09 16:56  灰太狼的梦想  阅读(1330)  评论(0编辑  收藏  举报