2012-04-17 49 views
1

我跟隨MVC音樂商店類似。 http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-9MVC3 db.SaveChanges()INSERT語句錯誤

當我創建orderDetails時,出現內部異常錯誤。

你能幫我什麼意思? 「INSERT語句與FOREIGN KEY約束\」FK_OrderDetails_Product \「衝突。數據庫\」rentalDB \「,表\」dbo.Product \「,列'productId'中發生衝突。\ r \ n聲明已被終止。「

我需要檢查SQL Server嗎?我不知道爲什麼它會發生錯誤..

你能給我一些建議嗎?我給你一些我的代碼。

請幫幫我。謝謝。

public int CreateOrder(Order order) 
    { 
     decimal orderTotal = 0; 

     var cartItems = GetCartItems(); 

     // Iterate over the items in the cart, adding the order details for each 
     foreach (var item in cartItems) 
     { 
      var orderDetail = new OrderDetails 
      { 
       productId = item.Product.productId, 
       orderId = order.orderId, 
       unitPrice = item.priceValue, 
       rentalPeriod = item.rentalPeriod, 
       startDate = item.dateCreated.AddDays(2), 
       endDate = item.dateCreated.AddDays(2 + item.rentalPeriod), 
       quantity = item.count 
      }; 

      // Set the order total of the shopping cart 
      orderTotal += (item.count * item.priceValue); 

      db.OrderDetails.Add(orderDetail); 

     } 

     // Set the order's total to the orderTotal count 
     order.total = orderTotal; 

     // Save the order 
     db.SaveChanges(); //I have error in here!!! 

     // Empty the shopping cart 
     EmptyCart(); 

     // Return the OrderId as the confirmation number 
     return order.orderId; 
    } 

這裏是視圖模型

public class ShoppingCartViewModel 
{ 
    public List<Cart> CartItems { get; set; } 
    public decimal CartTotal { get; set; } 
} 

這裏是車

public class Cart 
{ 
    [Key] 
    public int recordId { get; set; } 
    public string cartId { get; set; } 
    public int productId { get; set; } 
    public decimal priceValue { get; set; } 
    public int count { get; set; } 
    public int rentalPeriod { get; set; } 
    public DateTime dateCreated { get; set; } 
    public virtual Product Product { get; set; } 
} 

下面是產品

public class Product 
{ 
    [Key] public int productId { get; set; } 

    [Required(ErrorMessage = "Please select category")] 
    public int categoryId { get; set; } 

    [Required(ErrorMessage = "Please fill in model name")] 
    [DisplayName("Model name")] 
    public String model { get; set; } 

    [DisplayName("Description")] 
    public String description { get; set; } 

    [DisplayName("Original price")] 
    public decimal price { get; set; } 

    [Required(ErrorMessage = "Please fill in stock of product")] 
    [DisplayName("Stock")] 
    public int stock { get; set; } 
    public virtual Category Category { get; set; } 
} 

回答

0

我沒有設置FK在訂單明細..

這就是我之前得到的錯誤。

當我在OrderDetails和Order之間創建FK時,它將工作。