更新语句对linq不起作用
本文关键字:不起作用 linq 语句 更新 | 更新日期: 2023-09-27 18:06:32
我简直疯了,因为我要更新与类别表和产品表相关的表…但我没有成功……
我有这些表
product product_id
product_name
product_description
product_price
product_image
category category_id
catgory_name
category_desc
我已经这样做了更新表....使用实体框架…
private void btnSave_Click(object sender, EventArgs e)
{
if (lblHiddenmode.Text == "Edit")
{
using (var dbcontext = new TsgEntities())
{
pictureBox1.Enabled = true;
pictureBox1.Visible = true;
Image image = pictureBox1.Image;
byte[] bit = null;
bit = imageToByteArray(image);
product1 pd = new product1();
string category = cbcategorytypes.Text;
string categorydesc = tbCategoryDescription.Text;
var c = new category { category_Name = category, category_Description = categorydesc };
pd.product_Name = tbProductName.Text;
decimal price = Convert.ToDecimal(tbProductPrice.Text);
pd.product_Price = price;
pd.product_Description = tbProductdescription.Text;
pd.product_Image = bit;
pd.category = c;
dbcontext.SaveChanges();
this.Close();
}
}
}
注意:我正在更新产品名称,其中一个具有product_id为4和category_id = 4
,但它会显示在这个语句pd。我得到product_id = "0"和category_id = "0"
我做错了,当更新表与类别表。update语句
上面的代码将生成插入,而不是更新。为了执行更新,首先需要从上下文中检索product1
实例。
我不知道你的上下文看起来像什么,所以我不能发布确切的代码,但它会是这样的:
product1 pd = dbcontext.protucts.Where(p => p.productid == 4
&& p.categoryid == 4).First();
你可以做你的改变,并调用dbcontext.SaveChanges()
,它应该更新你的记录
您实际上并没有将对象添加到您的上下文中。
你需要这样做:
dbcontext.products.AddObject(pd1);