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):
app
EF會驗證StudentName的屬性值的長度,若是大於50個字符長度,就報錯:EF 6中:System.Data.Entity.Validation.DbEntityValidationException
,EF Core中Microsoft.EntityFrameworkCore.DbUpdateException
asp.net
請注意:StringLength特性,還能夠用在ASP.NET MVC中,用來驗證屬性的值,瞭解更多,請看這篇文章:Implement Validations in ASP.NET MVC 。測試