您当前的位置: 首页 > 

暂无认证

  • 0浏览

    0关注

    100378博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

[EF]DbEntityValidationException

发布时间:2019-06-12 13:50:50 ,浏览量:0

[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();

在这里插入图片描述

关注
打赏
1655516835
查看更多评论
立即登录/注册

微信扫码登录

0.0646s