请单击以进行评分并提供反馈
MSDN
MSDN Library
.NET 开发
先前版本
System.Data
DataTable 类
DataTable 方法
Load 方法
 Load 方法 (IDataReader, LoadOption)
全部折叠/全部展开 全部折叠
此页面仅适用于
Microsoft Visual Studio 2005/.NET Framework 2.0

同时提供下列产品的其他版本:
.NET Framework 类库
DataTable.Load 方法 (IDataReader, LoadOption)

注意:此方法在 .NET Framework 2.0 版中是新增的。

通过所提供的 IDataReader,用某个数据源的值填充 DataTable。如果 DataTable 已包含行,则从数据源传入的数据将根据 loadOption 参数的值与现有的行合并。

命名空间:System.Data
程序集:System.Data(在 system.data.dll 中)

Visual Basic(声明)
Public Sub Load ( _
    reader As IDataReader, _
    loadOption As LoadOption _
)
Visual Basic(用法)
Dim instance As DataTable
Dim reader As IDataReader
Dim loadOption As LoadOption

instance.Load(reader, loadOption)
C#
public void Load (
    IDataReader reader,
    LoadOption loadOption
)
C++
public:
void Load (
    IDataReader^ reader, 
    LoadOption loadOption
)
J#
public void Load (
    IDataReader reader, 
    LoadOption loadOption
)
JScript
public function Load (
    reader : IDataReader, 
    loadOption : LoadOption
)

参数

reader

提供一个或多个结果集的 IDataReader

loadOption

LoadOption 枚举的值,该值指示已存在于 DataTable 中的行如何与共享同一主键的传入行合并。

Load 方法使用加载的 IDataReader 中的第一个结果集,并在成功完成后,将读取器的位置设置为下一个结果集(如果有的话)。转换数据时,Load 方法将同样的转换规则用作 Fill 方法。

IDataReader 实例加载数据时,Load 方法必须考虑下面三个具体问题:架构、数据和事件操作。处理架构时,Load 方法可能会遇到如下表所述的情况。对于所有导入的结果集,都会发生相应的架构操作,即使结果集不包含任何数据也是如此。

条件

行为

DataTable 没有架构。

Load 方法根据来自导入的 IDataReader 的结果集推断架构。

DataTable 具有一个架构,但该架构与加载的架构不兼容。

Load 方法引发一个异常,该异常对应于当试图将数据加载到不兼容的架构中时发生的特定错误。

架构兼容,但加载的结果集架构包含 DataTable 中不存在的列。

Load 方法向 DataTable 的架构添加额外的列。如果 DataTable 中的对应列与加载的结果集在值上不兼容,此方法将引发一个异常。该方法还为所有添加的列从结果集中检索约束信息。仅在当前的 DataTable 在加载操作开始时不包含任何列的情况下,才使用此约束信息(主键约束除外)。

架构兼容,但加载的结果集架构包含的列数少于 DataTable 中包含的列数。

如果某个缺少的列定义了默认值,或者列的数据类型可为空值,则 Load 方法将允许添加行,并用默认值或空值来替代缺少的列。如果不能使用默认值或空值,则 Load 方法将引发异常。如果没有提供特定的默认值,则 Load 方法将空值用作暗含的默认值。

考虑 Load 方法在数据操作方面的行为之前,请注意:DataTable 中的每一行都同时维护每一列的当前值和原始值。这些值可能相同,也有可能不同。如果自填充 DataTable 之后行中的数据发生更改,则会出现后一种情况。有关更多信息,请参见 行状态与行版本

在此方法调用中,指定的 LoadOption 参数影响对传入数据的处理。Load 方法应如何处理与现有行具有相同主键的加载行呢?它应修改当前值、原始值,还是两者都修改?这些问题以及其他更多问题都由 loadOption 参数控制。

如果现有的行和传入的行包含对应的主键值,将使用其当前行状态值来处理行,否则将该行视为新行。

就事件操作而言,RowChanging 事件在每一行更改之前发生,RowChanged 事件在每一行更改之后发生。在每一种情况下,传递到事件处理程序的 DataRowChangeEventArgs 实例的 Action 属性都包含与事件关联的特定操作的有关信息。该操作值会根据加载操作之前的行状态相应地变化。在每一种情况下,两个事件都会发生,并且每个事件的操作相同。操作可能应用于每一行的当前版本和/或原始版本,具体取决于当前的行状态。

下表显示对每个 LoadOption 值调用 Load 方法时该方法的行为,以及这些值如何与正在加载的行的状态进行交互。最后一行(标记为“Not present”)描述了与任何现有行都不匹配的传入行的行为。该表中的每个单元格描述了一行中某个字段的当前值和原始值,以及在 Load 方法完成之后值的 DataRowState

现有的 DataRowState

Upsert

OverwriteChanges

PreserveChanges(默认行为)

Added

当前值 = <传入值>

原始值 = -<不可用>

状态 = <Added>

行操作 = 更改

当前值 = <传入值>

原始值 = <传入值>

状态 = <Unchanged>

行操作 = 更改当前值和原始值

当前值 = <现有值>

原始值 = <传入值>

状态 = <Modified>

行操作 = 更改原始值

Modified

当前值 = <传入值>

原始值 = <现有值>

状态 = <Modified>

行操作 = 更改

当前值 = <传入值>

原始值 = <传入值>

状态 = <Unchanged>

行操作 = 更改当前值和原始值

当前值 = <现有值>

原始值 = <传入值>

状态 = <Modified>

行操作 = 更改原始值

Deleted

(加载不影响删除的行)

当前值 = ---

原始值 = <现有值>

状态 = <Deleted>

(添加具有以下特性的新行)

当前值 = <传入值>

原始值 = <不可用>

状态 = <Added>

行操作 = 添加

撤销删除和

当前值 = <传入值>

原始值 = <传入值>

状态 = <Unchanged>

行操作 = 更改当前值和原始值

当前值 = <不可用>

原始值 = <传入值>

状态 = <Deleted>

行操作 = 更改原始值

Unchanged

当前值 = <传入值>

原始值 = <现有值>

若新值与现有值相同,则

状态 = <Unchanged>

行操作 = 无

否则

状态 = <Modified>

行操作 = 更改

当前值 = <传入值>

原始值 = <传入值>

状态 = <Unchanged>

行操作 = 更改当前值和原始值

当前值 = <传入值>

原始值 = <传入值>

状态 = <Unchanged>

行操作 = 更改当前值和原始值

(未提供)

当前值 = <传入值>

原始值 = <不可用>

状态 = <Added>

行操作 = 添加

当前值 = <传入值>

原始值 = <传入值>

状态 = <Unchanged>

行操作 = 更改当前值和原始值

当前值 = <传入值>

原始值 = <传入值>

状态 = <Unchanged>

行操作 = 更改当前值和原始值

可以通过使用诸如 ReadOnlyAutoIncrement 的属性来约束 DataColumn 中的值。Load 方法处理此类列的方式与列属性所定义的行为一致。DataColumn 上的只读约束仅适用于内存中发生的更改。如果需要,Load 方法会改写只读列值。

如果调用 Load 方法时指定了 OverwriteChanges 或 PreserveChanges 选项,则假定数据从 DataTable 的主数据源传入,且 DataTable 将跟踪更改并能够将更改传播回数据源。如果选择 Upsert 选项,则假定数据从一个辅助数据源传入,如中间层组件提供的数据,用户可能更改过此数据。此情况下,假定目的是在 DataTable 中聚合一个或多个数据源的数据,然后可能会将数据传播回主数据源。LoadOption 参数用于确定主键比较所使用的行的特定版本。下表提供了详细信息。

加载选项

用于主键比较的 DataRow 版本

OverwriteChanges

当原始版本存在时,为原始版本,否则为当前版本

PreserveChanges

当原始版本存在时,为原始版本,否则为当前版本

Upsert

当当前版本存在时,为当前版本,否则为原始版本

下面的示例演示调用 Load 方法涉及到的几个问题。首先,该示例着重于架构问题,包括从加载的 IDataReader 推断架构,然后处理不兼容的架构以及包含缺失列或其他列的架构。此示例随后着重于数据问题,包括处理各个加载选项。

Visual Basic
Sub Main()
  Dim table As New DataTable()

  ' This example examines a number of scenarios involving the
  '  DataTable.Load method.
  Console.WriteLine("Load a DataTable and infer its schema:")

  ' Retrieve a data reader, based on the Customers data. In
  ' an application, this data might be coming from a middle-tier
  ' business object:
  Dim reader As New DataTableReader(GetCustomers())

  ' The table has no schema. The Load method will infer the 
  ' schema from the IDataReader:
  table.Load(reader)
  PrintColumns(table)

  Console.WriteLine(" ============================= ")
  Console.WriteLine( _
      "Load a DataTable from an incompatible IDataReader:")

  ' Create a table with a single integer column. Attempt
  ' to load data from a reader with a schema that is 
  ' incompatible. Note the exception, determined
  ' by the particular incompatibility:
  table = GetIntegerTable()
  reader = New DataTableReader(GetStringTable())
  Try
    table.Load(reader)
  Catch ex As Exception
    Console.WriteLine(ex.GetType.Name & ":" & ex.Message())
  End Try

  Console.WriteLine(" ============================= ")
  Console.WriteLine( _
      "Load a DataTable with an IDataReader that has extra columns:")

  ' Note that loading a reader with extra columns adds
  ' the columns to the existing table, if possible:
  table = GetIntegerTable()
  reader = New DataTableReader(GetCustomers())
  table.Load(reader)
  PrintColumns(table)

  Console.WriteLine(" ============================= ")
  Console.WriteLine( _
      "Load a DataTable with an IDataReader that has missing columns:")

  ' Note that loading a reader with missing columns causes 
  ' the columns to be filled with null data, if possible:
  table = GetCustomers()
  reader = New DataTableReader(GetIntegerTable())
  table.Load(reader)
  PrintColumns(table)

  ' Demonstrate the various possibilites when loading data into
  ' a DataTable that already contains data.
  Console.WriteLine(" ============================= ")
  Console.WriteLine("Demonstrate data considerations:")
  Console.WriteLine("Current value, Original value, (RowState)")
  Console.WriteLine(" ============================= ")
  Console.WriteLine("Original table:")

  table = SetupModifiedRows()
  DisplayRowState(table)

  Console.WriteLine(" ============================= ")
  Console.WriteLine("Data in IDataReader to be loaded:")
  DisplayRowState(GetChangedCustomers())

  PerformDemo(LoadOption.OverwriteChanges)
  PerformDemo(LoadOption.PreserveChanges)
  PerformDemo(LoadOption.Upsert)

  Console.WriteLine("Press any key to continue.")
  Console.ReadKey()
End Sub

Private Sub DisplayRowState(ByVal table As DataTable)
  For i As Integer = 0 To table.Rows.Count - 1
    Dim current As Object = "--"
    Dim original As Object = "--"
    Dim rowState As DataRowState = table.Rows(i).RowState

    ' Attempt to retrieve the current value, which doesn't exist
    ' for deleted rows:
    If rowState <> DataRowState.Deleted Then
      current = table.Rows(i)("Name", DataRowVersion.Current)
    End If

    ' Attempt to retrieve the original value, which doesn't exist
    ' for added rows:
    If rowState <> DataRowState.Added Then
      original = table.Rows(i)("Name", DataRowVersion.Original)
    End If
    Console.WriteLine("{0}: {1}, {2} ({3})", i, _
      current, original, rowState)
  Next
End Sub

Private Function GetChangedCustomers() As DataTable
  ' Create sample Customers table.
  Dim table As New DataTable

  ' Create two columns, ID and Name.
  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(Integer))
  table.Columns.Add("Name", GetType(String))

  ' Set the ID column as the primary key column.
  table.PrimaryKey = New DataColumn() {idColumn}

  table.Rows.Add(New Object() {0, "XXX"})
  table.Rows.Add(New Object() {1, "XXX"})
  table.Rows.Add(New Object() {2, "XXX"})
  table.Rows.Add(New Object() {3, "XXX"})
  table.Rows.Add(New Object() {4, "XXX"})
  table.AcceptChanges()
  Return table
End Function

Private Function GetCustomers() As DataTable
  ' Create sample Customers table.
  Dim table As New DataTable

  ' Create two columns, ID and Name.
  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(Integer))
  table.Columns.Add("Name", GetType(String))

  ' Set the ID column as the primary key column.
  table.PrimaryKey = New DataColumn() {idColumn}

  table.Rows.Add(New Object() {0, "Mary"})
  table.Rows.Add(New Object() {1, "Andy"})
  table.Rows.Add(New Object() {2, "Peter"})
  table.AcceptChanges()
  Return table
End Function

Private Function GetIntegerTable() As DataTable
  ' Create sample table with a single Int32 column.
  Dim table As New DataTable

  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(Integer))

  ' Set the ID column as the primary key column.
  table.PrimaryKey = New DataColumn() {idColumn}

  table.Rows.Add(New Object() {4})
  table.Rows.Add(New Object() {5})
  table.AcceptChanges()
  Return table
End Function

Private Function GetStringTable() As DataTable
  ' Create sample table with a single String column.
  Dim table As New DataTable

  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(String))

  ' Set the ID column as the primary key column.
  table.PrimaryKey = New DataColumn() {idColumn}

  table.Rows.Add(New Object() {"Mary"})
  table.Rows.Add(New Object() {"Andy"})
  table.Rows.Add(New Object() {"Peter"})
  table.AcceptChanges()
  Return table
End Function

Private Sub PerformDemo(ByVal optionForLoad As LoadOption)

  ' Load data into a DataTable, retrieve a DataTableReader containing
  ' different data, and call the Load method. Depending on the
  ' LoadOption value passed as a parameter, this procedure displays
  ' different results in the DataTable.
  Console.WriteLine(" ============================= ")
  Console.WriteLine("table.Load(reader, {0})", optionForLoad)
  Console.WriteLine(" ============================= ")

  Dim table As DataTable = SetupModifiedRows()
  Dim reader As New DataTableReader(GetChangedCustomers())
  AddHandler table.RowChanging, New _
      DataRowChangeEventHandler(AddressOf HandleRowChanging)

  table.Load(reader, optionForLoad)
  Console.WriteLine()
  DisplayRowState(table)
End Sub

Private Sub PrintColumns( _
   ByVal table As DataTable)

  ' Loop through all the rows in the DataTableReader.
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(row(col).ToString() & " ")
    Next
    Console.WriteLine()
  Next
End Sub

Private Function SetupModifiedRows() As DataTable
  ' Fill a DataTable with customer info, and 
  ' then modify, delete, and add rows.

  Dim table As DataTable = GetCustomers()
  ' Row 0 is unmodified.
  ' Row 1 is modified.
  ' Row 2 is deleted.
  ' Row 3 is added.
  table.Rows(1)("Name") = "Sydney"
  table.Rows(2).Delete()
  Dim row As DataRow = table.NewRow
  row("ID") = 3
  row("Name") = "Melony"
  table.Rows.Add(row)

  ' Note that the code doesn't call
  ' table.AcceptChanges()
  Return table
End Function

Private Sub HandleRowChanging(ByVal sender As Object, _
      ByVal e As System.Data.DataRowChangeEventArgs)
  Console.WriteLine( _
      "RowChanging event: ID = {0}, action = {1}", e.Row("ID"), e.Action)
End Sub
C#
static void Main()
{
    // This example examines a number of scenarios involving the 
    // DataTable.Load method.
    Console.WriteLine("Load a DataTable and infer its schema:");

    // The table has no schema. The Load method will infer the 
    // schema from the IDataReader:
    DataTable table = new DataTable();

    // Retrieve a data reader, based on the Customers data. In
    // an application, this data might be coming from a middle-tier
    // business object:
    DataTableReader reader = new DataTableReader(GetCustomers());

    table.Load(reader);
    PrintColumns(table);

    Console.WriteLine(" ============================= ");
    Console.WriteLine(
        "Load a DataTable from an incompatible IDataReader:");

    // Create a table with a single integer column. Attempt
    // to load data from a reader with a schema that is 
    // incompatible. Note the exception, determined
    // by the particular incompatibility:
    table = GetIntegerTable();
    reader = new DataTableReader(GetStringTable());
    try
    {
        table.Load(reader);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.GetType().Name + ":" + ex.Message);
    }

    Console.WriteLine(" ============================= ");
    Console.WriteLine(
        "Load a DataTable with an IDataReader that has extra columns:");

    // Note that loading a reader with extra columns adds
    // the columns to the existing table, if possible:
    table = GetIntegerTable();
    reader = new DataTableReader(GetCustomers());
    table.Load(reader);
    PrintColumns(table);

    Console.WriteLine(" ============================= ");
    Console.WriteLine(
        "Load a DataTable with an IDataReader that has missing columns:");

    // Note that loading a reader with missing columns causes 
    // the columns to be filled with null data, if possible:
    table = GetCustomers();
    reader = new DataTableReader(GetIntegerTable());
    table.Load(reader);
    PrintColumns(table);

    // Demonstrate the various possibilites when loading data into
    // a DataTable that already contains data.
    Console.WriteLine(" ============================= ");
    Console.WriteLine("Demonstrate data considerations:");
    Console.WriteLine("Current value, Original value, (RowState)");
    Console.WriteLine(" ============================= ");
    Console.WriteLine("Original table:");

    table = SetupModifiedRows();
    DisplayRowState(table);

    Console.WriteLine(" ============================= ");
    Console.WriteLine("Data in IDataReader to be loaded:");
    DisplayRowState(GetChangedCustomers());

    PerformDemo(LoadOption.OverwriteChanges);
    PerformDemo(LoadOption.PreserveChanges);
    PerformDemo(LoadOption.Upsert);

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

private static void DisplayRowState(DataTable table)
{
    for (int i = 0; i <= table.Rows.Count - 1; i++)
    {
        object current = "--";
        object original = "--";
        DataRowState rowState = table.Rows[i].RowState;

        // Attempt to retrieve the current value, which doesn't exist
        // for deleted rows:
        if (rowState != DataRowState.Deleted)
        {
            current = table.Rows[i]["Name", DataRowVersion.Current];
        }

        // Attempt to retrieve the original value, which doesn't exist
        // for added rows:
        if (rowState != DataRowState.Added)
        {
            original = table.Rows[i]["Name", DataRowVersion.Original];
        }
        Console.WriteLine("{0}: {1}, {2} ({3})", i, 
            current, original, rowState);
    }
}

private static DataTable GetChangedCustomers()
{
    // Create sample Customers table.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name", typeof(string));

    // Set the ID column as the primary key column.
    table.PrimaryKey = new DataColumn[] { idColumn };

    table.Rows.Add(new object[] { 0, "XXX" });
    table.Rows.Add(new object[] { 1, "XXX" });
    table.Rows.Add(new object[] { 2, "XXX" });
    table.Rows.Add(new object[] { 3, "XXX" });
    table.Rows.Add(new object[] { 4, "XXX" });
    table.AcceptChanges();
    return table;
}

private static DataTable GetCustomers()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name", typeof(string));

    // Set the ID column as the primary key column.
    table.PrimaryKey = new DataColumn[] { idColumn };

    table.Rows.Add(new object[] { 0, "Mary" });
    table.Rows.Add(new object[] { 1, "Andy" });
    table.Rows.Add(new object[] { 2, "Peter" });
    table.AcceptChanges();
    return table;
}

private static DataTable GetIntegerTable()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));

    // Set the ID column as the primary key column.
    table.PrimaryKey = new DataColumn[] { idColumn };

    table.Rows.Add(new object[] { 4 });
    table.Rows.Add(new object[] { 5 });
    table.AcceptChanges();
    return table;
}

private static DataTable GetStringTable()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(string));

    // Set the ID column as the primary key column.
    table.PrimaryKey = new DataColumn[] { idColumn };

    table.Rows.Add(new object[] { "Mary" });
    table.Rows.Add(new object[] { "Andy" });
    table.Rows.Add(new object[] { "Peter" });
    table.AcceptChanges();
    return table;
}

private static void PerformDemo(LoadOption optionForLoad)
{

    // Load data into a DataTable, retrieve a DataTableReader containing
    // different data, and call the Load method. Depending on the
    // LoadOption value passed as a parameter, this procedure displays
    // different results in the DataTable.
    Console.WriteLine(" ============================= ");
    Console.WriteLine("table.Load(reader, {0})", optionForLoad);
    Console.WriteLine(" ============================= ");

    DataTable table = SetupModifiedRows();
    DataTableReader reader = new DataTableReader(GetChangedCustomers());
    table.RowChanging +=new DataRowChangeEventHandler(HandleRowChanging);

    table.Load(reader, optionForLoad);
    Console.WriteLine();
    DisplayRowState(table);
}

private static void PrintColumns(DataTable table)
{
    // Loop through all the rows in the DataTableReader
    foreach (DataRow row in table.Rows)
    {
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Console.Write(row[i] + " ");
        }
        Console.WriteLine();
    }
}

private static DataTable SetupModifiedRows()
{
    // Fill a DataTable with customer info, and 
    // then modify, delete, and add rows.

    DataTable table = GetCustomers();
    // Row 0 is unmodified.
    // Row 1 is modified.
    // Row 2 is deleted.
    // Row 3 is added.
    table.Rows[1]["Name"] = "Sydney";
    table.Rows[2].Delete();
    DataRow row = table.NewRow();
    row["ID"] = 3;
    row["Name"] = "Melony";
    table.Rows.Add(row);

    // Note that the code doesn't call
    // table.AcceptChanges()
    return table;
}

static void HandleRowChanging(object sender, DataRowChangeEventArgs e)
{
    Console.WriteLine(
        "RowChanging event: ID = {0}, action = {1}", e.Row["ID"], e.Action);
}

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

.NET Framework

受以下版本支持:2.0

.NET Compact Framework

受以下版本支持:2.0
社区内容   什么是社区内容?
添加新内容 RSS  批注
Processing
© 2009 Microsoft Corporation 版权所有。 保留所有权利 | 商标 | 隐私权声明
Page view tracker