保存我的实体时抛出EntityValidationException

时间:2014-03-12 07:08:30

标签: entity-framework asp.net-mvc-4 c#-4.0

我在catch (Exception e)中调试时收到此消息。当用户填写所有信息时,Address and Payment View将获得SalesOrderID并重定向到完整视图。但它完成时并没有显示完成。

[HttpPost]
        public ActionResult AddressAndPayment(SalesOrderHeader order,Customer customer, Address address ,FormCollection values)
        {
             ViewBag.PersonType = new SelectList(new[] { "EM", "SC", "VC", "IN" } // work
                                                    .Select(x => new { value = x, text = x }),
                                                    "value", "text");
            try
            {
                if (string.Equals(values["PromoCode"], PromoCode, StringComparison.OrdinalIgnoreCase) == false)
                {
                    return View(order);
                }
                else
                {
                    order.AccountNumber = User.Identity.Name;
                    order.OrderDate = DateTime.Now;
                    address.ModifiedDate = DateTime.Now; // maybe this error
                    order.Address.PostalCode = "12345";

                    //Save Order
                    BikeDBs.SalesOrderHeaders.Add(order);
                    try
                    {
                        BikeDBs.SaveChanges();
                    }
                    catch (DbEntityValidationException e)
                    {
                        foreach (var entityValidationErrors in e.EntityValidationErrors)
                        {
                            foreach (var validationError in entityValidationErrors.ValidationErrors)
                            {
                                Console.WriteLine("Properties: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                            }
                        }
                    }
                    //Process Order
                    var cart = ShoppingCart.GetCart(this.HttpContext);
                    cart.CreateOrder(order);
                    //cart.CreateOrder(order1);
                    return RedirectToAction("Complete", new { id = order.SalesOrderID });
                }
            }
            catch (Exception exception)
            {
                //Invalid - redisplay with errors
                return View(order);
            }

我想要的只是在保存Order时,它会重定向到Complete。但在这种情况下,它不是。这里是Address模型:

public partial class Address
    {
        public Address()
        {
            this.SalesOrderHeaders = new HashSet<SalesOrderHeader>();
            this.SalesOrderHeaders1 = new HashSet<SalesOrderHeader>();
        }

        public int AddressID { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string City { get; set; }
        public int StateProvinceID { get; set; }
        public string PostalCode { get; set; }
        public System.Guid rowguid { get; set; }
        [Required()]
        public Nullable<System.DateTime> ModifiedDate { get; set; }

        public virtual StateProvince StateProvince { get; set; }
        public virtual ICollection<SalesOrderHeader> SalesOrderHeaders { get; set; }
        public virtual ICollection<SalesOrderHeader> SalesOrderHeaders1 { get; set; }
    }

什么是解决方案以及如何解决?

2 个答案:

答案 0 :(得分:1)

你可以使用ModelState轻松地做到这一点,它应该抓住它。如果没有,我将代码添加到catch块中以捕获它并使用ModelState.AddModelError再次显示错误页面。

 [HttpPost]
public ActionResult AddressAndPayment(SalesOrderHeader order,Customer customer, Address address ,FormCollection values)
{
    ViewBag.PersonType = new SelectList(new[] { "EM", "SC", "VC", "IN" } // work
                                                .Select(x => new { value = x, text = x }),
                                                "value", "text");
    if(ModelState.IsValid)
    {
        try
        {
            if (string.Equals(values["PromoCode"], PromoCode, StringComparison.OrdinalIgnoreCase) == false)
            {
                return View(order);
            }
            else
            {
                order.AccountNumber = User.Identity.Name;
                order.OrderDate = DateTime.Now;
                order.Address.PostalCode = values["PostalCode"];

                //Save Order
                BikeDBs.SalesOrderHeaders.Add(order);
                try
                {
                    BikeDBs.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    foreach (var entityValidationErrors in e.EntityValidationErrors)
                    {
                        foreach (var validationError in entityValidationErrors.ValidationErrors)
                        {
                            // If this far add errors to model errors and show view again.
                            ModelState.AddModelError(validationError.PropertyName, validationError.ErrorMessage);
                            Console.WriteLine("Properties: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }
                    return View(order);
                }
                //Process Order
                var cart = ShoppingCart.GetCart(this.HttpContext);
                cart.CreateOrder(order);
                //cart.CreateOrder(order1);
                return RedirectToAction("Complete", new { id = order.SalesOrderID });
            }
        }
        catch (Exception exception)
        {
            //Invalid - redisplay with errors
            return View(order);
        }
    }
    return View(order);
}

答案 1 :(得分:1)

对于我的回答,我假设属性PostalCodePersonType属于string类型,并定义为not nullable

我认为您收到的错误消息清楚地说明了问题所在。属性PostalCodePersonType是必需的,这意味着他们需要的值不是null

因此,当您不将属性设置为null以外的值并尝试保存实体时,您将收到错误消息。

要修复它,您可以将属性设置为某些值(可能是默认值),或者您必须更改EntityModel以指定这些属性为nullable