[英]The given value of type String from the data source cannot be converted to type int of the specified target column.'
[英]The given value of type String from the data source cannot be converted to type int of the specified target column
我试图从xml文件中读取值,然后使用bulkcopy将数据插入到我的数据库中。
我正在使用一个自定义类:
class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int ShowsNumber { get; set; }
public int VisitNumber { get; set; }
public int Cancellation { get; set; }
}
我读了这样的数据:
List<Customer> customersList =
(
from e in XDocument.Load(file).Root.Elements("cust")
select new Customer
{
CustomerID = (int)e.Attribute("custid"),
FirstName = (string)e.Attribute("fname"),
LastName = (string)e.Attribute("lname"),
ShowsNumber = (int)e.Attribute("count_noshow"),
VisitNumber = (int)e.Attribute("count_resos"),
Cancellation = (int)e.Attribute("count_cancel"),
}).ToList();
然后我将customersList
插入到这样的数据表中:
DataTable dataTable = getBasicDataTable();
for (int i = 0; i < customersList.Count; i++)
{
DataRow datarows = dataTable.NewRow();
datarows[0] = customersList[i].CustomerID;
datarows[1] = customersList[i].FirstName;
datarows[2] = customersList[i].LastName;
datarows[3] = customersList[i].ShowsNumber;
datarows[4] = customersList[i].VisitNumber;
datarows[5] = customersList[i].Cancellation;
dataTable.Rows.Add(datarows);
}
然后我将数据插入我的数据库,如下所示:
但我得到了这个例外
using (SqlBulkCopy sbc = new SqlBulkCopy(GetConnectionString()))
{
sbc.DestinationTableName = XMLReader.databaseTable;
sbc.WriteToServer(dataTable);
}
数据源中String类型的给定值无法转换为指定目标列的int类型。
如你所见,当我从我的xml中提取数据时,我已经使用了强制转换为int
和string
,它正在工作。 那么为什么在插入数据库时我得到了那个例外?
为了给你整个代码,这是getBasicDataTable
函数
private DataTable getBasicDataTable()
{
DataTable dataTable = new DataTable();
dataTable.Clear();
dataTable.Columns.Add("customerID");
dataTable.Columns.Add("firstName");
dataTable.Columns.Add("lastName");
dataTable.Columns.Add("showsNumber");
dataTable.Columns.Add("visitNumber");
dataTable.Columns.Add("cancellation");
return dataTable;
}
你需要为整到指定列在定义datatable
。 像这样:-
dataTable.Columns.Add("customerID", typeof(int));
编辑:
我怀疑的另一个原因可能是你绑定数据表的方式(我的意思是列的顺序)与数据库表的绑定方式不匹配。 原因是我认为默认映射不是Name to Name而不是SqlBulkCopy
Index to Index。 所以请重新检查您的数据库表顺序,它应该如下: -
CustomerID (INT)
FirstName (VARCHAR\NVARCHAR)
LastName (VARCHAR\NVARCHAR)
ShowsNumber (INT)
VisitNumber (INT)
Cancellation (INT)
据我所知,你需要在数据表上设置列的类型,否则它将设定字符串(因为几乎所有东西都可以这样转换)。
在设置值之前,请尝试:
dataTable.Columns[2].Type = typeof (int);
或者,您可以在定义列时指定它:
dataTable.Columns.Add("ShowsNumber", typeof(int));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.