繁体   English   中英

使用更新语句在Linq to Entities中更新表时遇到问题,但未更新表

[英]Having a problem updating table in Linq to Entities with update statement but not updating the table

我有一个带有添加,编辑和保存按钮的表单。 该表单还具有一个datagridview。

我这样做是为了更新现有产品实体并添加新产品实体,然后在datagridview中显示更改的数据。

当我单击编辑按钮时,将显示保存按钮,并执行我在保存按钮中编写的语句。

新产品实体添加就好。

我的问题是,当我单击编辑按钮时,会将新行添加到datagridview中,而不是更新同一行。

在实体框架中添加到表之前,有什么方法可以检查表中可用产品是否正在更新或添加新产品的条件?

    private void btnSave_Click(object sender, EventArgs e)
    {

        pictureBox1.Enabled = true;
        pictureBox1.Visible = true;
        Image image = pictureBox1.Image;
        byte[] bit = null;

        bit = imageToByteArray(image);
        product1 pd = new product1();

        string category = tbCategoryName.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;


        tsgentity.SaveChanges();
        EquipmentFinder equipment = new EquipmentFinder();            
        equipment.productgridview.Refresh();           
        this.Close();
        equipment.ShowDialog(this);           

   }

这只是一个例子。 您需要做的是使用linq从正在编辑/保存的集合中提取当前对象,然后对检索到的对象进行更改,然后更新即

public bool UpdateCustomer(Customer customer){   
    Customer cust = entities.Customers.FirstOrDefault(c => c.ID == customer.ID);  
    cust.Forname = customer.Forename;   
    cust.Surname = customer.Surname   
    entities.SaveChanges(); 
}

您是否检查了这些按钮的事件处理程序? 它们是否连接到正确的按钮? 听起来您的“编辑”按钮正在触发新产品的事件处理程序,听起来像“添加”按钮正在触发用于编辑产品的事件处理程序。 我绝对会先检查一下,而不是寻找一种解决方法或黑客手段来容忍这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM