问:
以下代码:
var dtInstTotal = dtExternal.AsEnumerable()
.Union(dtEmployed.AsEnumerable())
.OrderBy(d => d.Field<string>("emp_name"));
dtInst = dtInstTotal.CopyToDataTable();//exception
抛出异常:
Value was either too large or too small for an Int16.Couldn't store <103930> in emp_num Column. Expected type is Int16. ---> System.OverflowException: Value was either too large or too small for an Int16.
最佳答案
我怀疑 dtExternal
对 emp_num
有一个short
类型,而 dtEmployed
有一些其他类型(int
, long
或可能只是 ushort
) - 或者反之亦然。 CopyToDataTable
只使用包含它看到的第一行的第一个表中的类型,然后当它遇到来自不同的表。来自 the docs :
The schema of the destination table is based on the schema of the first DataRow row in the source sequence. The table metadata is extracted from the DataRow metadata and the table values from the column values of the DataRow.
基本上:确保您的两个原始表具有相同的架构。
编辑:我们不知道您填充两个原始 DataTable
的方法是什么样的 - 但您可能会发现,通过首先创建 DataTable
,显式设置emp_num
的类型,然后 填充表格,这样就可以了。
您甚至可以不理会原来的方法,使用正确的模式构建一个新的DataTable
,然后调用
dtInstTotal.CopyToDataTable(tableWithCorrectSchema, LoadOption.PreserveChanges);
关于c# - 复制到数据表时,值对于 Int16 来说太大或太小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8738930/