[英]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.