我有两张桌子orders
和orderdetails
表订单(PK = id,orderno 上的唯一索引)
|id|orderno|
| 1|1000 |
| 2|1001 |
表 orderdetails (PK = id)
|id|orderid|item|qty|
| 1| 1|ABC | 3|
| 2| 1|XYZ | 4|
现在我想查询数据:
SELECT o.orderno, od.item, od.qty
FROM orders o
INNER JOIN orderdetails od ON o.orderno = od.order
返回:
|orderno|item|qty|
|1000 |ABC | 3|
|1000 |XYZ | 4|
但是,如果我使用以下代码将结果加载到 DataTable 中,则会失败:
var connectionString = "Server=localhost;Database=orders;Uid=root;";
var commandText = "SELECT o.orderno, od.item, od.qty" + Environment.NewLine +
"FROM orders o" + Environment.NewLine +
"INNER JOIN orderdetails od ON o.orderno = od.order";
var reader = MySqlHelper.ExecuteReader(connectionString, commandText);
var table = new DataTable("OrdersQuery");
table.Fill(reader); // throws ConstraintException
问题是,那
table.Constraints[0]
是UniqueConstraints
orderno 列上的一个。大概是因为
reader.GetSchemaTable()
有一个IsUnique=true
orderno 条目(在基表中为真,但在连接查询中不为真)。
更糟糕的是,这也无济于事:
table.BeginLoadData(); // msdn docs claim that this should disable constraints
table.Load(reader);
table.EndLoadData();
任何想法如何解决这一问题?
堆栈跟踪:
System.Data.ConstraintException Was Unhandled.
Message=Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Source=System.Data
StackTrace:
bei System.Data.DataTable.EnableConstraints()
bei System.Data.DataTable.set_EnforceConstraints(Boolean value)
bei System.Data.DataTable.EndLoadData()
bei System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue)
bei System.Data.Common.DataAdapter.Fill(DataTable[] dataTables, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)
bei System.Data.Common.LoadAdapter.FillFromReader(DataTable[] dataTables, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)
bei System.Data.DataTable.Load(IDataReader reader, LoadOption loadOption, FillErrorEventHandler errorHandler)
bei System.Data.DataTable.Load(IDataReader reader)