【发布时间】:2014-11-26 00:35:34
【问题描述】:
我有一个 WCF 服务,它接受 DataTable,并将它们合并到现有数据中。以前,这只需要添加行,效果很好,但是有了删除行的新要求(无论它们是否真的存在),我遇到了问题。
由于在 SQL 服务器和 DataTable 中存在问题的行数可能非常大,我不想加载现有行并将它们与我的 DataTable 进行比较.
我的代码执行以下操作:
public Statistics ApplyChanges(DataTable changeData)
{
var stats = new Statistics();
if (changeData.IsEmpty)
{
Trace.WriteLine(string.Format("Client {0} had nothing to do; called ApplyChanges anyway. (Should normally not happen.)", ClientId));
return stats;
}
FooDataSet ds = new FooDataSet();
ds.Bar.Merge(changeData, false, MissingSchemaAction.Ignore);
foreach (var row in ds.Bar)
{
// This is the new requirement. If the incoming row's 'Value' is null,
// delete the row from the database, or, if the row doesn't exist, do
// nothing.
if (row.Field<string>("Value") == null)
row.Delete();
else
row.SetAdded();
}
int changesApplied;
using (var scope = new TransactionScope())
{
BarTableAdapter barAdapter = new BarTableAdapter();
changesApplied = barAdapter.Update(ds.Bar);
scope.Complete();
}
stats.ChangesApplied = changesApplied;
stats.ChangesFailed = ds.Bar.Count(r => r.HasErrors);
Trace.WriteLine(string.Format("Client {0} applied {1} changes, had {2} changes fail.", ClientId, changesApplied, stats.ChangesFailed));
return stats;
}
现在,我(也许是天真的)想添加,如果一行不存在,它会被默默忽略,或者最坏的情况是设置HasErrors 属性,但没有。相反,该行
changesApplied = barAdapter.Update(ds.Bar);
引发异常DBConcurrencyException,并带有以下消息:“并发冲突:DeleteCommand 影响了预期的 1 条记录中的 0 条。”
我明白为什么当您关心并发性时会收到一个很好的通知,但我不需要。我只想删除该行,或者忽略它丢失。
【问题讨论】:
-
你怎么知道它是否存在?只有数据库知道吗?
-
我不在乎它是否存在。所以我猜,是吗?问题是,运行删除不存在的行的 SQL 是完全合法的(你只会得到 0 个受影响的行),这就是我想要的行为。
标签: c# .net sql-server datatable tableadapter