문제

Q:

The following code:

        var dtInstTotal = dtExternal.AsEnumerable()
                    .Union(dtEmployed.AsEnumerable())
                    .OrderBy(d => d.Field<string>("emp_name"));

        dtInst = dtInstTotal.CopyToDataTable();//exception

throw an 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.

도움이 되었습니까?

해결책

I suspect that dtExternal has a short type for emp_num, whereas dtEmployed has some other type (int, long or maybe just ushort) - or maybe vice versa. CopyToDataTable just uses the types from the first table containing the first row it sees, and then it's having problems when it comes across a value for a column with the same name from a different table. From 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.

Basically: make sure your two original tables have the same schema.

EDIT: We don't know what your methods to populate the two original DataTables look like - but you may find that by creating the DataTable first, explicitly setting the type of emp_num, and then filling the table, that will be okay.

You could even leave your original methods alone, and build a new DataTable with the right schema, then call

dtInstTotal.CopyToDataTable(tableWithCorrectSchema, LoadOption.PreserveChanges);

다른 팁

i think the datatable structure in dtInst or dtInstTotal for emp_num is int16 change it to int32

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top