[英]SubmitChanges not updating, but inserts new record. LINQ to SQL
我很難通過LINQ將數據更新到SQL,插入新記錄效果很好。
代碼正確地插入了新行並添加了主鍵,這是我要更新(更改數據庫中已存在的值)該數據庫未更新的那一行的問題,這是該問題的另一部分無法正常工作的代碼。 這很奇怪,因為數據庫已正確連接,並且DataContext插入了沒有問題的新行,因此可以正常工作。 檢查數據庫可以確認這一點。
這是代碼,
using System;
using System.Collections.Generic;
using System.Linq;
using Cost = Invoices.Tenant_Cost_TBL;
namespace Invoices
{
class CollectionGridEvents
{
static string conn = Settings.Default.Invoice_DbConnectionString;
public static void CostDataGridCellEditing(DataGridRowEditEndingEventArgs e)
{
using (DatabaseDataContext DataContext = new DatabaseDataContext(conn))
{
var sDselectedRow = e.Row.Item as Cost;
if (sDselectedRow == null) return;
if (sDselectedRow.ID == 0)
{
sDselectedRow.ID = DateTime.UtcNow.Ticks;
DataContext.Tenant_Cost_TBLs.InsertOnSubmit(sDselectedRow);
}
else
{
// these two lines are just for debuging
long lineToUpdateID = 636154619329526649; // this is the line to be updated primary key
long id = sDselectedRow.ID; // this is to check the primary key on selected line is same
// these 3 lines are to ensure I am entering actual data into the DB
int? amount = sDselectedRow.Cost_Amount;
string name = sDselectedRow.Cost_Name;
int? quantity = sDselectedRow.Cost_Quantity;
sDselectedRow.Cost_Amount = amount;
sDselectedRow.Cost_Name = name;
sDselectedRow.Cost_Quantity = quantity;
}
try
{
DataContext.SubmitChanges();
}
catch (Exception ex)
{
Alert.Error("Did not save", "Error", ex);
}
}
}
}
}
我從這里調用方法,
private void CostDataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
CollectionGridEvents.CostDataGridCellEditing(e);
}
從數據庫lineToUpdateID
復制lineToUpdateID,並在那里檢查當前選擇的行主鍵是否相同,所以我知道我正在嘗試更新同一行。
我在SO上瀏覽了許多相同類型的問題,例如這個Linq-to-Sql SubmitChanges沒有更新字段……為什么? 。 但是仍然離發現問題出處還很近。
任何想法將不勝感激。
編輯: Cost
只是using Cost = Invoices.Tenant_Cost_TBL;
簡稱using Cost = Invoices.Tenant_Cost_TBL;
你不能這樣做。 您需要將記錄從數據庫中取出,然后更新該記錄。 然后將其保存回來。 像這樣:
else
{
// first get it
var query =
from ord in DataContext.Tenant_Cost_TBLs
where ord.lineToUpdateID = 636154619329526649
select ord;
// then update it
// Most likely you will have one record here
foreach (Tenant_Cost_TBLs ord in query)
{
ord.Cost_Amount = sDselectedRow.Cost_Amount;
// ... and the rest
// Insert any additional changes to column values.
}
}
try
{
DataContext.SubmitChanges();
}
catch (Exception ex)
{
Alert.Error("Did not save", "Error", ex);
}
這是您可以遵循的示例。
或者,如果您不想首先選擇,則可以使用直接查詢。
DataContext.ExecuteCommand("update Tenant_Cost_TBLs set Cost_Amount =0 where ...", null);
您的對象(成本)未附加到數據庫上下文。 您應該附加它,然后保存更改。 在這里檢查解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.