【发布时间】:2016-04-29 09:54:02
【问题描述】:
我有一个DataSet 并从其中的两个来源读取数据。一个来自 XML 文件的表和另一个来自 Firebird SQL 数据库的表。我试图得到的只是一个表,其中包含 XML 文件中的所有列以及单个表中 SQL 数据中的几个字段。两个表中都有相同的唯一键字段,因此可以轻松合并。我想将此表的所有字段绑定到表单上的字段。
是否可能像描述的那样,或者我没有看到有更简单的解决方案来解决我的问题?
编辑: 为了展示我尝试做的一些额外代码。
DataSet dataSet = new DataSet();
DataTable table1 = new DataTable("test1", "test1");
table1.Columns.Add("id");
table1.Columns.Add("name");
table1.Columns[0].Unique = true;
table1.Rows.Add(new object[2] { 1, "name1" });
table1.Rows.Add(new object[2] { 2, "name2" });
DataTable table2 = new DataTable("test2", "test2");
table2.Columns.Add("id");
table2.Columns.Add("thing");
table2.Columns[0].Unique = true;
table2.Rows.Add(new object[2] { 1, "thing1" });
table2.Rows.Add(new object[2] { 2, "thing2" });
dataSet.Tables.Add(table1);
dataSet.Tables[0].Merge(table2, false);
当我运行这段代码时,我得到一个ConstraintException。当我删除 id 字段上的唯一值时,它会用所有需要的列填充列表,但其中一行包含来自 table1 的数据,另一行包含 table2 数据。如何合并它们?
编辑 2: 我尝试在实时数据中使用 PrimaryKey 解决方案,如下所示。
xmlData.Tables[0].PrimaryKey = new[] { xmlData.Tables[0].Columns["usnr"] };
dbData.PrimaryKey = new[] { dbData.Columns["usid"] };
xmlData.Tables[0].Merge(dbData, true, MissingSchemaAction.Add);
xmlData 是来自 XML 文件的 DataSet。它有 id、usnr 和其他一些字段。 dbData 是一个DataTable,其中包含来自 db 的数据,它具有 id、usid、name 和其他一些字段。 id 字段与我的数据无关。正如我使用GetType() 测试的那样,usnr 和 usid 字段都是表中的字符串。
当我现在添加 xmlData.Tables[0].Merge(dbData, true, MissingSchemaAction.Add); 时,它会抛出 DataException
<target>.ID and <source>.ID have conflicting properties: DataType property mismatch.
在写这篇文章时,我意识到两个表中的 id 字段不同,但无论如何我都不需要它们,所以在更改 primaryKey 条目和合并之前删除了该列。现在我得到一个NullReferenceException,里面没有更多信息。表都很好,里面有数据,现在哪里来的异常?
【问题讨论】: