原文鏈接:https://www.entityframeworktutorial.net/code-first/maxlength-minlength-dataannotations-attribute-in-code-first.aspx MaxLength特性指定了屬性的值所允許的最大值,然後在 ...
MaxLength特性指定了屬性的值所允許的最大值,然後在資料庫中就生成相應列的最大值。MaxLength特性可以應用於實體的String類型的屬性和byte[]數組類型的屬性上。
如果MaxLength特性,應用在其他類型的屬性上就報錯,例如下麵的圖中例子:
using System.ComponentModel.DataAnnotations;
public class Student
{
public int StudentID { get; set; }
[MaxLength(50)]
public string StudentName { get; set; }
}
上面代碼例子中,MaxLength(50)應用在StudentName屬性上,指定StudentName的屬性值不能超過50個字元長度。
EF將會檢查標識了MaxLength特性的屬性值,如果長度超過了指定的長度,就會報錯,EF6報錯:System.Data.Entity.Validation.DbEntityValidationException ,EF Core報錯:Microsoft.EntityFrameworkCore.DbUpdateException.
請註意:MaxLength特性,同樣可以用在ASP.NET MVC中,用於驗證屬性的值,瞭解更多詳情請看這篇文章: Implement Validations in ASP.NET MVC。