将购物车项目添加到数据库出错

时间:2016-08-30 14:58:48

标签: c# asp.net-mvc entity-framework asp.net-mvc-4 ef-code-first

我正在撰写商务应用程序,并且遇到了令人沮丧的错误,并没有告诉我实际错误是什么。

Error Message Details

这是正在运行的代码

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddToCart(int product_ID)
{
    if (db.Products.Any(product => product.Product_ID == product_ID))
    {
        //var successfulAddToCart = false;
        var cartItem = new Cart();

       // cartItem.CartID = Guid.NewGuid();

        if (Request.IsAuthenticated)
        {
            var Customer = db.Customers.FirstOrDefault(customer => customer.Email == User.Identity.Name);
            cartItem.Customer = Customer;
            cartItem.CustomerID = Customer.Customer_ID;
        }                    
        else//not logged in, need to remember them somehow
        {
            // add a cookie for a guest user so we can save their cart for some time.
            var CartCookie = new HttpCookie("Cart", Guid.NewGuid().ToString());
            CartCookie.Expires.AddDays(2);
            Request.Cookies.Add(CartCookie);
            cartItem.Customer = new Customer();
            cartItem.CustomerID = null;
        }

        //obviously not checked out since we just added to cart
        cartItem.IsCheckedOut = false;
        cartItem.Quantity = 1;
        //one to one with product, so grab the first sku you find.
        var Sku = db.SKU_Table.SingleOrDefault(sku => sku.Product_ID == product_ID);
        cartItem.Sku = Sku;
        cartItem.SkuID = Sku.SKU_ID;
        //if everything is okay, save the changes to the database
        if (ModelState.IsValid)
        {
            db.Cart.Add(cartItem);
            db.SaveChanges();
        }


        //return a content string that displays success or failure
        return Content("Add to cart was successful");
    }
    return Content("Add to cart was not successful");//unsuccessful add 
}

据我所知,我的模型完全有效,我不知道问题的根源是什么。我可以发布购物车项目对象的值,如果这将有所帮助。错误信息并没有真正帮助,我也没有看到我的模型状态出现任何问题,特别是因为它已经过去了。

这是购物车型号

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace SeniorProjectMVC.Models
{
    [Table("Cart")]
    public class Cart
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }
        public Guid CartID { get; set; }
        public int SkuID { get; set; }
        public virtual Sku Sku { get; set; }
        [Required]
        public int Quantity { get; set; } 
        public int? CustomerID { get; set; }
        public virtual Customer Customer { get; set; }
        public bool IsCheckedOut { get; set; }
    }
}

1 个答案:

答案 0 :(得分:0)

我可以看到您已将模型中的CustomerID设为可为空,但也尝试在您的数据库中使您的客户ID字段为Nullable,或允许Customer ID字段取空值。