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


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

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

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

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 here

現在,如果你保存數據的時候,沒有填入StudentName屬性的值,就會報System.Data.Entity.Validation.DbEntityValidationException異常:對於EF Core會報這個Microsoft.EntityFrameworkCore.DbUpdateException異常。
請注意:Required 同樣可以用於ASP.NET MVC中,作為驗證特性,了解更多在MVC中的實現方式,請看這個文章:Implement Validations in ASP.NET MVC


免責聲明!

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



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