zoukankan      html  css  js  c++  java
  • EntityFramework 学习 一 Validate Entity

    可以为实体实现自定义验证,重写DBContext中的个ValidateEntity方法

    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);
    }
    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);
            }
        }
    }
  • 相关阅读:
    分布式session管理解决方案
    RabbitMQ知识汇总
    RabbitMQ之集群模式总结
    Flexbox参数详解
    CSS Lint
    javascript中的defer属性和async属性
    简介BFC
    GIT 牛刀小试 (第二发)
    GIT 牛刀小试 (第一发)
    如何让浏览器支持HTML5标签
  • 原文地址:https://www.cnblogs.com/lanpingwang/p/6623139.html
Copyright © 2011-2022 走看看