Should AcceptChanges() be called every time a new row is added?(每次添加新行时都应该调用 AcceptChanges() 吗?)
问题描述
推荐
while (reader.Read())
{
table.Rows.Add(
new object[] { reader[0], reader[1], reader[2], reader[3] }
);
table.AcceptChanges();
}
或
while (reader.Read())
{
table.Rows.Add(
new object[] { reader[0], reader[1], reader[2], reader[3] }
);
}
table.AcceptChanges();
注意 table.AcceptChanges 的放置位置.
Note where the table.AcceptChanges is placed.
编辑 1
这里是代码块:
protected void Page_Load(object sender, EventArgs e)
{
IDataReader reader = cust.GetCustomerOrderSummary("99999");
using (DataSet ds = new DataSet())
{
using (DataTable table =
new DataTable { TableName = "OrderSummary" })
{
DataColumn idColumn = table.Columns.Add("number", typeof(int));
table.Columns.Add("name", typeof(string));
table.Columns.Add("quantity", typeof(int));
table.Columns.Add("prev_quantity", typeof(int));
table.PrimaryKey = new DataColumn[] { idColumn };
while (reader.Read())
{
table.Rows.Add(
new object[]{ reader[0], reader[1], reader[2], reader[3] }
);
table.AcceptChanges();
}
ds.Tables.Add(table);
rptCustomerOrder report =
new rptCustomerOrder { DataSource = ds };
ReportViewer1.Report = report;
}
}
}
<小时>
编辑 2
在阅读了 MSDN 文章 here 我决定根据以下语句(来自文章)将 AcceptChanges() 置于循环之外:
EDIT 2
After reading the MSDN article here I decided to place the AcceptChanges() outside the loop based on the following statement (from the article):
在 DataTable 级别调用 AcceptChanges 会导致调用每个 DataRow 的 AcceptChanges 方法.
Calling AcceptChanges at the DataTable level causes the AcceptChanges method for each DataRow to be called.
推荐答案
添加新行后调用AcceptChanges
实际上会变成你新添加的DataRow的
DataRowState
从 Added
到 Unchanged
.如果您继续使用它,您可能失去对新添加行的跟踪,并且在持久化时.ADO.NET 无法识别需要插入数据库的行.所以明智地选择这个选项,你甚至可能不需要它.
Calling AcceptChanges
after adding new row will actually turn the DataRowState
of your newly added DataRow
from Added
to Unchanged
. If you go with it you might lose the tracking of your newly added rows and at the time of persistance. ADO.NET would not be able to identify the rows which needs to be inserted in the database. So choose this option wisely you might not even require it.
这篇关于每次添加新行时都应该调用 AcceptChanges() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:每次添加新行时都应该调用 AcceptChanges() 吗?
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01