电贺!我正在尝试创建DataRow并将其添加到现有的DataSet / DataTable。我遇到的问题是表似乎没有正确传播。我知道桌子存在但是它不会给我任何东西但是作为回报。有什么想法吗?
代码:
var TownDataSet = new DataSet("newDataSet");
var checkDataSet = new DataSet();
var checkDataTable = new DataTable();
var dataTableName = "someDataSet";
checkDataSet = TownDataSet.Clone();
checkDataTable = TownDataSet.Tables[dataTableName];
Console.WriteLine("STEP 4 " + checkDataSet.DataSetName);
Console.WriteLine("STEP 5 " + checkDataSet.Tables.Count);
Console.WriteLine("STEP 6 " + checkDataTable.TableName);
当我到达第6步时出错:
STEP 4 newDataSet
STEP 5 7
DataTableInsertTemp: System.NullReferenceException: Object reference not set to an instance of an object.
答案 0 :(得分:0)
让我们分析一下:
var TownDataSet = new DataSet("newDataSet");
var checkDataSet = new DataSet();
var checkDataTable = new DataTable();
var dataTableName = "someDataSet";
checkDataSet = TownDataSet.Clone();
checkDataTable = TownDataSet.Tables[dataTableName];
其中:
所以:
请改为尝试:
var dataTableName = "someDataSet";
var TownDataSet = new DataSet("newDataSet");
var checkDataSet = new DataSet();
/* add a new DataTable to the DataSet.Tables collection */
checkDataSet.Tables.Add(new DataTable(dataTableName));
/* maybe you need to add some columns too */
checkDataSet.Tables[dataTableName].Columns.Add(new DataColumn("columnA", typeof(int)));
checkDataSet.Tables[dataTableName].Columns.Add(new DataColumn("columnB", typeof(string)));
/* create and initialize a new DataRow for the Tables[dataTableName] table */
var r = TownDataSet.Tables[dataTableName].NewRow();
r["columnA"] = 1;
r["columnB"] = "Some value";
/* add it to the Tables[dataTableName].Rows collection */
TownDataSet.Tables[dataTableName].Rows.Add(r);
修改强>
有几种方法可以将数据库映射到数据集。我可以建议你一些:
POCO - Plain Old CLR Object。那就是为每个表创建一个实体类,将表的字段映射到类的属性中。
Object-Relational Mapping。它是一个将数据库表映射到类的框架层。 C#实现是NHibernate。
ADO.NET Tables Schema。您可以使用ADO.NET功能使用DataAdapter类将数据库的表架构定义导入到数据集中。
这是基本实施:
DataSet ds = new DataSet();
ds.Tables.Add(new DataTable("myTable"));
da.FillSchema(ds.Tables["mytable"], SchemaType.Source);
var dataTableName = "someDataSet";
var TownDataSet = new DataSet("newDataSet");
var checkDataSet = new DataSet();
/* add a new DataTable to the DataSet.Tables collection */
checkDataSet.Tables.Add(new DataTable(dataTableName));
/*
* Fit the sql statement and the connection string depending on your scenario
* Set the *Command, *Connection and *DataAdapter actual provider
*/
SqlCommand cmd = new SqlCommand("select * from myTable");
SqlConnection conn = new SqlConnection("my connection string");
SqlDataAdapter da = new SqlDataAdapter();
cmd.Connection = conn;
da.SelectCommand = cmd;
/* that's it: the datatable is now mapped with the corresponding db table structure */
da.FillSchema(checkDataSet.Tables[dataTableName], SchemaType.Source);