Validate Entity

You can write custom server side validation for any entity. To accomplish this, override ValidateEntity method of DBContext as shown below.

protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, System.Collections.Generic.IDictionary<object, object> items)
{
if (entityEntry.Entity is Student)
{
if (entityEntry.CurrentValues.GetValue<string>("StudentName") == "")
{
var list = new List<System.Data.Entity.Validation.DbValidationError>();
list.Add(new System.Data.Entity.Validation.DbValidationError("StudentName", "StudentName is required")); return new System.Data.Entity.Validation.DbEntityValidationResult(entityEntry, list);
}
}
return base.ValidateEntity(entityEntry, items);
}

As you can see in the above code, we are validating the Student entity. If StudentName is blank, then we are adding DBValidationError into DBEntityValidationResult. So whenever you call DBContext.SaveChanges method and you try to save Student entity without StudentName, then it will throw DbEntityValidationException. For example:

try
{
using (var ctx = new SchoolDBEntities())
{
ctx.Students.Add(new Student() { StudentName = "" });
ctx.Standards.Add(new Standard() { StandardName = "" }); ctx.SaveChanges();
}
}
catch (DbEntityValidationException dbEx)
{
foreach (DbEntityValidationResult entityErr in dbEx.EntityValidationErrors)
{
foreach (DbValidationError error in entityErr.ValidationErrors)
{
Console.WriteLine("Error Property Name {0} : Error Message: {1}",
error.PropertyName, error.ErrorMessage);
}
}
}

Entity Framework Tutorial Basics(40):Validate Entity的更多相关文章

  1. Entity Framework Tutorial Basics(4):Setup Entity Framework Environment

    Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet ...

  2. Entity Framework Tutorial Basics(42):Colored Entity

    Colored Entity in Entity Framework 5.0 You can change the color of an entity in the designer so that ...

  3. Entity Framework Tutorial Basics(27):Update Entity Graph

    Update Entity Graph using DbContext: Updating an entity graph in disconnected scenario is a complex ...

  4. Entity Framework Tutorial Basics(5):Create Entity Data Model

    Create Entity Data Model: Here, we are going to create an Entity Data Model (EDM) for SchoolDB datab ...

  5. Entity Framework Tutorial Basics(26):Add Entity Graph

    Add Entity Graph using DbContext: Adding entity graph with all new entities is a simple task. We can ...

  6. Entity Framework Tutorial Basics(1):Introduction

    以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...

  7. Entity Framework Tutorial Basics(32):Enum Support

    Enum in Entity Framework: You can now have an Enum in Entity Framework 5.0 onwards. EF 5 should targ ...

  8. Entity Framework Tutorial Basics(31):Migration from EF 4.X

    Migration from Entity Framework 4.1/4.3 to Entity Framework 5.0/6.0 To migrate your existing Entity ...

  9. Entity Framework Tutorial Basics(20):Persistence in Entity Framework

    Persistence in Entity Framework There are two scenarios when persisting an entity using EntityFramew ...

随机推荐

  1. Jam的计数法

    Jam的计数法 题目描述 Description Jam是个喜欢标新立异的科学怪人.他不使用阿拉伯数字计数,而是使用小写英文字母计数,他觉得这样做,会使世界更加丰富多彩.在他的计数法中,每个数字的位数 ...

  2. datetimefield和datefield的区别

    django创建关于时间的model时,有三个可选,datetimefield.datefield和timefield,这三个分别对应datetime.date.time对象,这三个对象都有共同的属性 ...

  3. Weblogic启动成功,控制台打不开

    有时候,我们在linux操作系统上成功启动了weblogic,也查看了7001端口的状态是开启的.但是访问weblogic控制台没有反应,也没有报错. 使用 netstat -ano | grep 7 ...

  4. 生产环境连接数据库失败:Cannot create PoolableConnectionFactory❨Got mins one from a read call❩

    生产环境发现有接口调不通,而且集中在两个节点,其他节点都没问题.抓取日志发现报错如下: Context initialization failed. org.springframework. bean ...

  5. java的Swing编程====实现鼠标双击一下==画图===getMouseClicked的方法

    总结: 使用匿名类,但是用实现接口的方式呢??? package com.aa; import java.awt.Color; import java.awt.Graphics; import jav ...

  6. 《拳皇98终极之战OL》系统分析

    转自:http://www.gameres.com/467959.html 游戏简述 <拳皇98终极之战OL>是由日本SNK官方正版授权,国内著名游戏公司北京掌趣科技与北京玩蟹科技开发,腾 ...

  7. Linux学习笔记 -- 磁盘的管理

    df df命令参数功能:检查文件系统的磁盘空间占用情况.可以利用该命令来获取硬盘被占用了多少空间,目前还剩下多少空间等信息. 语法: df [-ahikHTm] [目录或文件名] 选项与参数: -a ...

  8. git学习3 - 克隆远程库到本地 将本地库上传到git

    如何克隆远程版本库到本地 git clone URL 如何用命令将本地项目上传到git 1.(先进入项目文件夹)通过命令 git init 把这个目录变成git可以管理的仓库 (注意: cd C:/U ...

  9. IO模型比较分析

    异步IO(Asynchronous I/O) Linux下的asynchronous IO其实用得不多,从内核2.6版本才开始引入.先看一下它的流程: 用户进程发起read操作之后,立刻就可以开始去做 ...

  10. 浅谈 Python 的 with 语句 【转载】

    引言 with 语句是从 Python 2.5 开始引入的一种与异常处理相关的功能(2.5 版本中要通过 from __future__ import with_statement 导入后才可以使用) ...