c# - 复制到数据表时,值对于 Int16 来说太大或太小

标签 c# asp.net linq informix overflowexception

问:

以下代码:

        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.

最佳答案

我怀疑 dtExternalemp_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/

相关文章:

c# - telerik tabstrip 控件显示在其他选项卡中

c# - SqlBulkCopy 不工作

C# 以更好的方式使用数据库上下文和异常处理 (DRY)

c# - 如何从父级访问嵌套的用户控件 View 模型

c# - 在每个方法中初始化一个新的套接字是一件好事吗?

asp.net - 如何在 .net vb 中发送 POST?

LINQ:我们可以从层次结构创建一个平面列表吗

c# - 最接近数字的linq sql

linq - 如何在 Linq 中使用 OrderBy

c# - XmlException - 来自第 3 方的非法 XML;必须处理