我有两个表orders
和orderdetails
表订单(PK = id,orderno上的UNIQUE索引)
|id|orderno|
| 1|1000 |
| 2|1001 |
表顺序详细信息(PK = ID)
|id|orderid|item|qty|
| 1| 1|ABC | 3|
| 2| 1|XYZ | 4|
现在我想用以下查询数据:
SELECT o.orderno, od.item, od.qty
FROM orders o
内连接顺序详细信息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]
是orderno列上的
UniqueConstraints
。可能是因为reader.GetSchemaTable()
有一个orderno的
IsUnique=true
条目(在基表中为true,但对于联接查询而言为true)。更糟糕的是,这也无济于事:
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)
最佳答案
我有同样的问题,但是通过使用此文章:http://bugs.mysql.com/bug.php?id=65065(在底部)中的解决方法来解决:
cmd.CommandText = "SELECT cam.no_serie, t.mnt FROM trx t LEFT JOIN camn cam USING(id_camn) ";
MySqlDataReader dr = cmd.ExecuteReader();
DataSet ds = new DataSet();
DataTable dataTable = new DataTable();
ds.Tables.Add(dataTable);
ds.EnforceConstraints = false;
dataTable.Load(dr);
dr.Close();