实体状态值不能为null

时间:2018-10-09 15:18:22

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

我有两个表的订单和订单明细,并且我有订单的foriegn键。并且我正在将ordertotal插入订单表以及所有其他订单信息中的订单详细信息,但是我遇到此错误。请帮帮我,请告诉我硬件使用实体状态将值添加到前键表中。

enter image description here

这是我的保存订单控制器功能

[HttpPost]
    public ActionResult SaveOrder(FormCollection fc)
     {
        ResturantContext context = new ResturantContext();
        ShoppingCart myCart = (ShoppingCart)Session[WebUtil.CART];
        User u = (User)Session[WebUtil.USER];
        Order order = new Order();



        order.TotalAmount = myCart.TotalAmount;
        new OrderHandler().AddOrder(order);

        foreach (var m in myCart.Items)
        {
            OrderDetails od = new OrderDetails();
            od.ID = m.Id;
            od.Price =m.Price;
            od.Product_name = m.Name;
            od.Quantity = m.Quantity;
            od.Address = fc["Address"];
            od.City = fc["City"];
            od.DateOfOrder = DateTime.Now;
            od.UserName = u.FullName;
            od.Email = u.Email;

            od.ContactNo = fc["ContactNo"];
            od.Country = fc["Country"];

           new OrderHandler().AddOrderDetails(od);

        }
        Session.Remove(WebUtil.CART);
        return RedirectToAction("Index","Home");
    }

1 个答案:

答案 0 :(得分:1)

od.Order将始终为Null,因为您没有在代码中的任何位置进行设置。在调用od.Order = order

之前,至少尝试在循环内将其设置为OrderHandler().AddOrderDetails(od);