zoukankan      html  css  js  c++  java
  • Entity Framework Tutorial Basics(40):Validate Entity

    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);
            }
        }
    }
  • 相关阅读:
    cocoaPods 最新系统上的安装和基本使用图文笔记
    iOS cell左滑出现多个功能按钮(IOS8以后支持)
    JPA error org.hibernate.AnnotationException: No identifier specified for entity
    spring-boot Jpa配置
    Java中各种集合(字符串类)的线程安全性!!!
    kafka浅谈
    Redis 指令
    JVM监控及堆栈内存
    redis与mysql性能对比、redis缓存穿透、缓存雪崩
    分布式锁机制
  • 原文地址:https://www.cnblogs.com/purplefox2008/p/5649464.html
Copyright © 2011-2022 走看看