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

相关文章
相关标签/搜索