简体   繁体   English

在具有相同值的DataRow上调用SetField会导致更改吗?

[英]Calling SetField on a DataRow with the same value causes changes?

Somewhat confused here, the following code causes changes in the DataTable when I would not expect it to do so. 这里有些令人困惑,当我不希望以下代码引起更改时,以下代码会导致DataTable发生更改。 Is there no actual individual value change management inside of a DataTable? 数据表内部是否没有实际的个人价值变更管理? Or am I missing something? 还是我错过了什么?

var table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Rows.Add("Sample Name");
table.AcceptChanges();

table.Rows[0].SetField("Name", "Sample Name");

var changes = table.GetChanges();

// expecting null, actually returns changes

I would have expected internally the table to use some pre-built logic to determine whether or not the new value is indeed different from the current value. 我本来希望该表在内部使用一些预构建的逻辑来确定新值是否确实与当前值不同。

Why is it done like this? 为什么这样做呢?

When you modify content of a row, it updates the DataRow.RowState property, which can hold UnChanged , Added , Modified etc. Later DataTable.GetChanges filter out rows based on that row status. 当您修改行的内容时,它将更新DataRow.RowState属性,该属性可以保存UnChangedAddedModified等。稍后, DataTable.GetChanges根据该行的状态过滤掉行。 It is irrespective of the value . 它与价值无关

DataTable.GetChanges - MSDN DataTable.GetChanges-MSDN

Gets a copy of the DataTable containing all changes made to it since it was last loaded, or since AcceptChanges was called, filtered by DataRowState. 获取DataTable的副本,该副本包含自上次加载以来或自调用AcceptChanges以来对其所做的所有更改, 并由DataRowState过滤。

Also see: 另请参阅:

Row States and Row Versions - MSDN 行状态和行版本-MSDN

ADO.NET manages rows in tables using row states and versions. ADO.NET使用行状态和版本来管理表中的行。 A row state indicates the status of a row; 行状态指示行的状态; row versions maintain the values stored in a row as it is modified, including current, original, and default values. 行版本会保留修改后存储在行中的值,包括当前值,原始值和默认值。 For example, after you have made a modification to a column in a row, the row will have a row state of Modified , and two row versions: Current, which contains the current row values, and Original, which contains the row values before the column was modified. 例如, 对一行中的一列进行修改后,该行的行状态为Modified ,并且具有两个行版本:Current(包含当前行值)和Original(包含在行之前的行值)列已修改。

This is apparently a design feature as even calling the SetField() extension method with exactly the same object and then checking the field values in DataRowVersion.Original and DataRowVersion.Current you can find that they are still reference equal. 这显然是一种设计功能,甚至可以使用完全相同的对象调用SetField()扩展方法,然后检查DataRowVersion.OriginalDataRowVersion.Current的字段值,您会发现它们仍然引用相等。 There is no documentation describing a different behavior. 没有文档描述不同的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM