9.9 翻譯系列:數據注解特性之--MaxLength 【EF 6 Code-First系列】


原文鏈接:https://www.entityframeworktutorial.net/code-first/maxlength-minlength-dataannotations-attribute-in-code-first.aspx

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

MaxLength特性指定了屬性的值所允許的最大值,然后在數據庫中就生成相應列的最大值。MaxLength特性可以應用於實體的String類型的屬性和byte[]數組類型的屬性上。

如果MaxLength特性,應用在其他類型的屬性上就報錯,例如下面的圖中例子:
enter description here
enter description here

using System.ComponentModel.DataAnnotations;
    
public class Student
{
    public int StudentID { get; set; }
    [MaxLength(50)]
    public string StudentName { get; set; }
        
}

上面代碼例子中,MaxLength(50)應用在StudentName屬性上,指定StudentName的屬性值不能超過50個字符長度。
enter description here

EF將會檢查標識了MaxLength特性的屬性值,如果長度超過了指定的長度,就會報錯,EF6報錯:System.Data.Entity.Validation.DbEntityValidationException ,EF Core報錯:Microsoft.EntityFrameworkCore.DbUpdateException.

請注意:MaxLength特性,同樣可以用在ASP.NET MVC中,用於驗證屬性的值,了解更多詳情請看這篇文章: Implement Validations in ASP.NET MVC


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM