[EF]DbEntityValidationException

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

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章