gpt4 book ai didi

c# - 如何使用 TableMapping 而不是 TableName 填充数据集

转载 作者:太空宇宙 更新时间:2023-11-03 14:34:31 25 4
gpt4 key购买 nike

根据msdn http://msdn.microsoft.com/en-us/library/ks92fwwh.aspx

The DataTableMapping name can be passed in place of the DataTable name to the Fill method of the DataAdapter.

下面的代码是 TableName "Employee"

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;

public class MyClass
{
public static void Main()
{
OleDbConnection mySqlConnection =new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\data\nwind.Mdb");

OleDbCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "SELECT EmployeeID, FirstName, LastName " +
"FROM Employees AS Emp " +
"WHERE EmployeeID = 9";
OleDbDataAdapter mySqlDataAdapter = new OleDbDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();

DataTableMapping myDataTableMapping = mySqlDataAdapter.TableMappings.Add("Employees", "dtEmployee");

Console.WriteLine("myDataTableMapping.DataSetTable = " + myDataTableMapping.DataSetTable);
Console.WriteLine("myDataTableMapping.SourceTable = " + myDataTableMapping.SourceTable);

myDataTableMapping.ColumnMappings.Add("EmployeeID", "dtEmployeeId");
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet, "Employee");
mySqlConnection.Close();

DataTable myDataTable = myDataSet.Tables["dtEmployee"];
foreach (DataRow myDataRow in myDataTable.Rows)
{
Console.WriteLine("ID = " + myDataRow["dtEmployeeId"]);
Console.WriteLine("FirstName = " + myDataRow["FirstName"]);
Console.WriteLine("LastName = " + myDataRow["LastName"]);
}
Console.ReadLine();
}

}

如果我在 Fill 中传递“dtEmployee”

mySqlDataAdapter.Fill(myDataSet, "dtEmployee");

它说 dtEmployeeId 不属于数据表 dtEmployee !那么我该如何使用我的 ColumnMappings?

最佳答案

我认为您的论点顺序错误。来自 MSDN 文档:

The following example creates a DataTableMapping named AuthorsMapping for the Authors table.

workAdapter.TableMappings.Add("AuthorsMapping", "Authors");

我看起来像您正在为 dtEmployee 表创建一个名为 Employees 的 DataTableMapping。尝试:

DataTableMapping myDataTableMapping = mySqlDataAdapter.TableMappings.Add("dtEmployee", "Employees");

澄清一下,现在您正在创建一个名为Employees 的映射。然后,您将填充名为 dtEmployee 的 DataTable。由于 dtEMployeeId 在您的映射 Employees 而不是您的数据表 dtEmployee 上,因此它会抛出正确的错误“dtEmployeeId 不属于 datatable dt员工"

关于c# - 如何使用 TableMapping 而不是 TableName 填充数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1621286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com