[英]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.