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

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

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

Required特性能夠應用於一個實體的一個或多個屬性上面。EF將會爲標識Required特性的屬性,在數據庫表的列中生成不爲空的列。mvc

using System.ComponentModel.DataAnnotations;
    
public class Student
{
    public int StudentID { get; set; }
    [Required]
    public string StudentName { get; set; }
}

上面代碼中,Required特性,應用到了StudentName屬性上,因此EF API將會在Students表中建立一個不爲空的StudentName列:
enter description hereapp

如今,若是你保存數據的時候,沒有填入StudentName屬性的值,就會報System.Data.Entity.Validation.DbEntityValidationException異常:對於EF Core會報這個Microsoft.EntityFrameworkCore.DbUpdateException異常。
請注意:Required 一樣能夠用於ASP.NET MVC中,做爲驗證特性,瞭解更多在MVC中的實現方式,請看這個文章:Implement Validations in ASP.NET MVCasp.net

相關文章
相關標籤/搜索