我尝试使用linq更新数据库中的某些数据。我在以下方法中编写的所有其他代码都按预期工作,但标记行中的更新代码不起作用。数据库没有变化。我调试了它,我正在获得用户期望的值。唯一的问题是我期望在数据库中进行的更改。可能是什么问题?
private void addToCart()
{
FixbayDBDataContext db = new FixbayDBDataContext();
if (Session["CustomerAuthentication"] != null)
{
CartTbl cartTbl = new CartTbl();
CartShoeTbl csTbl = new CartShoeTbl();
int cusID = Convert.ToInt32(Session["CustomerAuthentication"]);
int shoeID = Convert.ToInt32(sizeDdl.Text);
var idQuery = from c in db.CartTbls.AsQueryable()
where c.CustomerID == cusID
select new{c.CartID,c.CustomerID};
var shoeQuery = from s in db.ShoeTbls.AsQueryable()
join m in db.ShoeModelTbls on s.ModelID equals m.ModelID
where s.ShoeID == shoeID
select new { s.ShoeID, m.Price };
int quantity = Convert.ToInt32(quantityDdl.Text);
double shoePrice = (double)shoeQuery.First().Price;
double totalPrice = quantity * shoePrice;
//int shoeID = (int)shoeQuery.First().ShoeID;
//int lastShoeID = 0;
if (idQuery.Any())
{
int cartID = (int)idQuery.FirstOrDefault().CartID;
var cartShoeQuery = from ca in db.CartShoeTbls.AsQueryable()
where ca.CartID == cartID && ca.ShoeID == shoeID
select ca;
if (cartShoeQuery.Any())
{
csTbl.Quantity += Convert.ToInt32(quantityDdl.Text);
db.SubmitChanges();
}
else
{
var cartQuery = from ca in db.CartTbls.AsQueryable()
where ca.CustomerID == cusID
select new { ca.CartID, ca.TotalPrice };
double currentTotal = (double)cartQuery.FirstOrDefault().TotalPrice;
currentTotal = currentTotal + totalPrice;
cartTbl.TotalPrice = currentTotal; //UPDATE LINE
db.SubmitChanges();
csTbl.CartID = cartQuery.First().CartID;
csTbl.ShoeID = shoeID;
csTbl.Quantity = Convert.ToInt32(quantityDdl.Text);
db.CartShoeTbls.InsertOnSubmit(csTbl);
db.SubmitChanges();
}
}
else
{
cartTbl.CustomerID = cusID;
cartTbl.TotalPrice = totalPrice;
db.CartTbls.InsertOnSubmit(cartTbl);
csTbl.CartID = cartTbl.CartID;
csTbl.ShoeID = shoeID;
csTbl.Quantity = quantity;
db.CartShoeTbls.InsertOnSubmit(csTbl);
db.SubmitChanges();
}
}
else
{
Response.Write("<script>alert('Please login before you start to shopping !');</script>");
}
}
答案 0 :(得分:1)
cartTbl
永远不会设置为属于数据库的任何值。这是您创建的new
cartTbl,它不在数据库中。您需要更改 in 数据库中的内容以更新数据库。