9.8 翻译系列:数据注解特性之--Required 【EF 6 Code-First系列】

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

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

猜你喜欢

转载自www.cnblogs.com/caofangsheng/p/10677516.html