每次添加新行时,应该调用AcceptChanges()吗? [英] Should AcceptChanges() be called every time a new row is added?

查看:542
本文介绍了每次添加新行时,应该调用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文章这里我决定将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 添加新行后,实际上会将 DataRowState 新添加的 DataRow 添加不变。如果您随身携带,您可能会丢失新添加的行的跟踪,并在持久性时丢失。 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()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆