Sqlbulkcopy异常仅在生产环境中存在



我有一个很奇怪的行为。当我在本地测试应用程序时,一切正常,使用IIS Express,最新版本的VisualStudio 2015 Update 3。

但是在Windows Server 2012的IIS8上运行的实时应用程序,有时不能。

有时我得到以下异常:

System.InvalidOperationException: The given value of type String from the data source cannot be converted to type nvarchar of the specified target column. ---> System.InvalidOperationException: String or binary data would be truncated.

我记录应用程序处理的数据,如果在生产中使用生成异常的完全相同的数据文件,并且我在本地机器(连接到生产DB)上运行它,它工作得很好。不例外。

异常的真正原因不可能是DB列的长度,因为我是逐个字段检查数据的。顺便说一下,如果它是字符串长度的问题,我也会在本地得到异常。

数据表的定义:

  var dt = new DataTable();
  dt.Columns.Add("gid", typeof(int));
  dt.Columns.Add("season", typeof(string));
  dt.Columns.Add("brand", typeof(string));
  dt.Columns.Add("brandid", typeof(string));
  dt.Columns.Add("pattern", typeof(string));
  dt.Columns.Add("width", typeof(string));
  dt.Columns.Add("ratio", typeof(string));
  dt.Columns.Add("diameter", typeof(string));
  dt.Columns.Add("load", typeof(string));
  dt.Columns.Add("speed", typeof(string));
  dt.Columns.Add("isrunflat", typeof(bool));
  dt.Columns.Add("price", typeof(decimal));
  dt.Columns.Add("original_descr", typeof(string));
  dt.Columns.Add("source", typeof(string));
  dt.Columns.Add("createdon", typeof(DateTime));
  dt.Columns.Add("updatedon", typeof(DateTime));
  dt.Columns.Add("eulgas", typeof(string));
  dt.Columns.Add("eulrai", typeof(string));
  dt.Columns.Add("eulnc", typeof(string));
  dt.Columns.Add("euldb", typeof(string));

这是数据库表的定义:

CREATE TABLE [dbo].[grabbed_zero](
    [gid] [bigint] NOT NULL,
    [season] [nvarchar](50) NOT NULL,
    [brand] [nvarchar](50) NOT NULL,
    [brandid] [nvarchar](50) NOT NULL,
    [pattern] [nvarchar](100) NOT NULL,
    [width] [nvarchar](10) NOT NULL,
    [ratio] [nvarchar](10) NOT NULL,
    [diameter] [nvarchar](10) NOT NULL,
    [load] [nvarchar](10) NOT NULL,
    [speed] [nvarchar](10) NOT NULL,
    [isrunflat] [int] NOT NULL,
    [price] [decimal](10, 2) NOT NULL,
    [original_descr] [nvarchar](100) NOT NULL,
    [source] [nvarchar](50) NOT NULL,
    [createdon] [datetime] NOT NULL,
    [updatedon] [datetime] NOT NULL,
    [EULGAS] [nvarchar](10) NOT NULL,
    [EULRAI] [nvarchar](10) NOT NULL,
    [EULNC] [nvarchar](10) NOT NULL,
    [EULDB] [nvarchar](10) NOT NULL,
)

我绞尽脑汁,但还是想不出是什么原因造成的。

有人知道吗?

最后我发现问题是由json反序列化引起的,它在发布模式和调试模式下的行为不同。

批量复制的数据文件最初是json格式的。

当我发现的时候,我只是做了一个nuget Update-Package - install的newton软件包(已经更新到最新版本),它解决了这个问题。

尝试使用以下代码添加字符串dataccolumn:

DataColumn d = new DataColumn(fieldname, typeof(string));
d.MaxLength = 10; //Specify max length
dt.Columns.Add(d);

所以当插入数据到dataTable时异常会被抛出你将指定列

最新更新