每天学一点,每天积累一点,进步就不止一点点!PS:好记性不如烂笔头,学会总结,学会思考~~~ ----要飞翔,必须靠自己!

灰太狼的梦想

好记性不如烂笔头,学会总结,学会思考~~~

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

posted @ 2019-04-09 16:01  灰太狼的梦想  阅读(1737)  评论(0编辑  收藏  举报