原创

[EF]DbEntityValidationException

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://david.blog.csdn.net/article/details/91512194
    [Table("Product")]
    public partial class Product
    {
        [Key]
        public int Id { get; set; }
        [Required(ErrorMessage = "必须指定商品名称")]
        public string Name { get; set; }

        [Range(10, 500, ErrorMessage = "商品价格范围 10-500")]
        public int Price { get; set; }
        [Range(10, 500, ErrorMessage = "商品价格范围 10-500")]
        public int SPrice { get; set; }




        //[Required]
        //public string Name { get; set; }

        //[Range(10, 500)]
        //public int Price { get; set; }
        //[Range(10, 500)]
        //public int SPrice { get; set; }
    }
            using (var context = new KTStoreContext())
            {
                try
                {
                    Product product = new Product
                    {
                        //Name = "Entity Framework 精要",
                        //Price = 40,
                        //SPrice = -120


                        Name = null,
                        Price = -40,
                        SPrice = -120
                    };
                    context.Product.Add(product);
                    int count = context.SaveChanges();
                    Console.WriteLine("添加{0}项数据 !", count);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\n错误信息:{0}\n", ex.Message);

                    if (ex is DbEntityValidationException)
                    {

                        foreach (var validationResult in ((DbEntityValidationException)ex).EntityValidationErrors)
                        {
                            foreach (var error in validationResult.ValidationErrors)
                            {
                                Console.WriteLine(" … {0}", error.ErrorMessage);
                            }
                        }
                    }

                    // override SaveChanges()
                    // Console.WriteLine(ex.Message);
                }
            }
            Console.ReadKey();

在这里插入图片描述

文章最后发布于: 2019-06-12 13:50:50
展开阅读全文
0 个人打赏

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 鲸 设计师: meimeiellie

分享到微信朋友圈

×

扫一扫,手机浏览