我有困难通过LINQ to SQL更新数据库,插入新记录可以正常工作。SubmitChanges不更新,但插入新记录。 LINQ to SQL
该代码正确插入一个新行并添加一个主键,我遇到的问题是当我去更新(chnage是一个已经在数据库中的值),数据库没有更新的同一行时,它是代码的其他部分无法正常工作。这是奇怪的B/C数据库正确连接,并通过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
从数据库dirrectly复制只是有要检查的当前选择行主键是相同的,所以我知道我正在尝试更新同一行。
我已经查看了很多相同类型的问题,例如这里的一个Linq-to-Sql SubmitChanges not updating fields … why?。但仍然没有更接近发现哪里出了问题。
任何想法将不胜感激。
编辑:Cost
是本using Cost = Invoices.Tenant_Cost_TBL;
对不起,我认为很明显,数据“成本”是我从数据库获得的记录的一部分,通过插入该行实际工作的事实。或者我误解了你?请参阅更新后的编辑问题。 – KyloRen
Linq to SQL不支持像那样的更新。您需要先从数据库中获取该记录,然后更新该记录并保存。现在,当您创建DatabaseDataContext时,您并没有将它从数据库中取出。 – CodingYoshi
@KyloRen请参阅更新 – CodingYoshi