我在一个表中插入数据,并希望更新另一个表的数据,就像我们在winforms c#中一样。我希望当有人购买产品时,其数量将在另一张表中更新。但我收到这个错误: “实体类型产品不是当前上下文模型的一部分。”
我的代码如下:
[HttpGet]
public ActionResult Purchase()
{
if (Session["userId"] != null)
{
int a = (int)Session["userId"];
var maxId = //(from k in mse.Orders where k.user_Id == a select k.Order_Id).Max();
mse.Orders.Where(r => r.user_Id == a).OrderByDescending(r => r.Order_Id).First();
ViewBag.oId = maxId.Order_Id;
var reg = (from abc in mse.Registerations where abc.Register_Id == a select abc).First();
ViewBag.shipAd = reg.shippingAddress;
ViewBag.quantity = maxId.Quantity;
TempData["quantity"] = ViewBag.quantity;
var prodId = maxId.Product_Id;
var pId = (from f in mse.Products where f.Product_Id == prodId select f).OrderByDescending(f => f.Product_Id).First();
ViewBag.price = pId.unitPrice;
}
return View();
}
[HttpPost]
public ActionResult Purchase(Purchase p)
{
if (Session["userId"] != null)
{
p.Register_Id = (int)Session["userId"];
int a = Convert.ToInt16(TempData["productId"]);
int b = Convert.ToInt16(TempData["quantity"]);
var subQuanitty = (from s in mse.Products where s.Product_Id == a select s).First();
int quantity = Convert.ToInt16(subQuanitty.Quantity) - b;
Products prod = new Products();
prod.Quantity = b.ToString();
updateProduct(prod);
if (ModelState.IsValid)
{
mse.Purchases.Add(p);
mse.SaveChanges();
return RedirectToAction("Status");
}
}
return View(p);
}
public void updateProduct(Products prod)
{
mse.Entry(prod).State = EntityState.Modified;
mse.SaveChanges();
}