9.10 翻譯系列:EF數據註解特性之StringLength【EF 6 Code-First系列】

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

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):
enter description hereapp

EF會驗證StudentName的屬性值的長度,若是大於50個字符長度,就報錯:EF 6中:System.Data.Entity.Validation.DbEntityValidationException,EF Core中Microsoft.EntityFrameworkCore.DbUpdateExceptionasp.net

請注意:StringLength特性,還能夠用在ASP.NET MVC中,用來驗證屬性的值,瞭解更多,請看這篇文章:Implement Validations in ASP.NET MVC測試

相關文章
相關標籤/搜索