【发布时间】:2016-11-23 02:21:21
【问题描述】:
我在通过 LINQ to SQL 更新数据库时遇到困难,插入新记录工作正常。
代码正确插入了一个新行并添加了一个主键,我遇到的问题是当我去更新(更改数据库中已经存在的值)数据库没有更新的同一行时,它是else 部分代码不能正常工作。这很奇怪,因为 DataContext 插入了一个没有问题的新行,所以 DB 已正确连接并运行。检查数据库证实了这一点。
这是代码,
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 是从数据库中直接复制的,用于检查当前选定的行主键是否相同,所以我知道我正在尝试更新同一行。
我在 SO 上查看了许多相同类型的问题,例如 Linq-to-Sql SubmitChanges not updating fields … why?。但仍然无法找出问题所在。
任何想法都将不胜感激。
编辑:Cost 只是这个using Cost = Invoices.Tenant_Cost_TBL; 的简写
【问题讨论】: