向 DataTable 添加/删除 DataRow 的正确方法是什么
我在从 DataTable 中添加和删除用于 DataAdapter.Update() 的 DataRows 时遇到问题。我不断收到并发错误,但我不知道哪里出了问题。
当我从数据表中添加和删除行时会发生这种情况。
目前,我添加如下行:
table.Rows.Add(new string{null /*pk*/, "composite_FK1", "composite_FK2", "composite_FK3"});
并删除数据表中的最后一个逻辑行,如下所示:
DataRow[] rows = table.Select(string.Empty, string.Empty, DataViewRowState.CurrentRows);
if (rows.Length > 0)
{
DataRow row = rows[rows.Length - 1];
if (row.RowState == DataRowState.Added)
{
// directly remove this row because it is not in the database yet
table.Rows.Remove(row);
}
else
{
// mark this row for deletion from the database
row.Delete();
}
}
经过几次添加和删除后,更新失败并出现并发异常。添加行的更好方法是什么?任何人都可以帮忙找出错误吗?谢谢。
I am facing problem adding and deleting DataRows from a DataTable that is meant for DataAdapter.Update(). I keep getting Concurrency error but I cannot figure where is wrong.
It happens when i add and delete rows from a DataTable.
At the moment, I add rows like this:
table.Rows.Add(new string{null /*pk*/, "composite_FK1", "composite_FK2", "composite_FK3"});
and i delete the last logical row in the DataTable like this:
DataRow[] rows = table.Select(string.Empty, string.Empty, DataViewRowState.CurrentRows);
if (rows.Length > 0)
{
DataRow row = rows[rows.Length - 1];
if (row.RowState == DataRowState.Added)
{
// directly remove this row because it is not in the database yet
table.Rows.Remove(row);
}
else
{
// mark this row for deletion from the database
row.Delete();
}
}
After a few add and deletes, Update fails with Concurrency Exception. What can be a better way to add rows? Anyone can help spot the error please? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将数据写入数据库(插入或更新),然后将数据从数据库读回到数据表中会更容易。
It is easier to write your data to the database (inserts or updates), then read the data back from the database into your data table.
对于每次添加和删除,您都使用 table.acceptchanges(),希望它能正常工作
For every adding and deleting u use table.acceptchanges(), hope it will work fine