原文链接: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):
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

相关文章:

  • 2022-01-27
  • 2021-12-26
  • 2021-11-23
  • 2021-10-13
  • 2021-09-14
  • 2019-03-31
  • 2019-03-31
  • 2022-03-09
猜你喜欢
  • 2021-11-21
  • 2022-01-23
  • 2021-08-31
  • 2021-11-20
  • 2022-01-13
  • 2021-08-12
  • 2021-05-30
相关资源
相似解决方案