這是我的第二篇文章。在從我的第一篇文章中學習使用Linq to SQL的奇妙之處後,我想嘗試從Excel工作表導入數據到我的SQL數據庫中。使用Linq導入Excel數據時,獲取指定的演員表無效
首先我的Excel工作表:
它包含4列即
- 貨號
- ItemSize
- ITEMPRICE
- UnitsSold
我有一個創建了一個數據庫表與以下fie LDS
table name ProductsSold
Id int not null identity --with auto increment set to true
ItemNo VarChar(10) not null
ItemSize VarChar(4) not null
ItemPrice Decimal(18,2) not null
UnitsSold int not null
現在,我創建了一個基於我的數據庫dal.dbml文件,我想用下面的代碼從Excel表中的數據導入到數據庫表。
一切正在發生點擊按鈕。
private const string forecast_query = "SELECT ItemNo, ItemSize, ItemPrice, UnitsSold FROM [Sheet1$]";
protected void btnUpload_Click(object sender, EventArgs e)
{
var importer = new LinqSqlModelImporter();
if (fileUpload.HasFile)
{
var uploadFile = new UploadFile(fileUpload.FileName);
try
{
fileUpload.SaveAs(uploadFile.SavePath);
if(File.Exists(uploadFile.SavePath))
{
importer.SourceConnectionString = uploadFile.GetOleDbConnectionString();
importer.Import(forecast_query);
gvDisplay.DataBind();
pnDisplay.Visible = true;
}
}
catch (Exception ex)
{
Response.Write(ex.Source.ToString());
lblInfo.Text = ex.Message;
}
finally
{
uploadFile.DeleteFileNoException();
}
}
}
// Now here is the code for LinqSqlModelImporter
public class LinqSqlModelImporter : SqlImporter
{
public override void Import(string query)
{
// importing data using oledb command and inserting into db using LINQ to SQL
using (var context = new WSDALDataContext())
{
using (var myConnection = new OleDbConnection(base.SourceConnectionString))
using (var myCommand = new OleDbCommand(query, myConnection))
{
myConnection.Open();
var myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
context.ProductsSolds.InsertOnSubmit(new ProductsSold()
{
ItemNo = myReader.GetString(0),
ItemSize = myReader.GetString(1),
ItemPrice = myReader.GetDecimal(2),
UnitsSold = myReader.GetInt32(3)
});
}
}
context.SubmitChanges();
}
}
}
有人可以告訴我,我在哪裏做錯誤或如果我失去了一些東西,但這是讓我瘋狂。
當我調試,我得到這個錯誤
when casting from a number the value must be a number less than infinity
我真的很感激
凡(上線),你得到的錯誤? – 2012-07-10 19:04:32
當我使用的調試器,它的顯示上爲它是context.ProductsSolds.InsertOnSubmit(新ProductsSold() { 貨號= myReader.GetString(0), ItemSize = myReader.GetString(1),所述 LinqSqlModelImporter線23 ItemPrice = myReader.GetDecimal(2), UnitsSold = myReader.GetInt32(3) }); – niceoneishere 2012-07-10 19:11:26
所以我想可能是它與GetDecimal或GetInt32的東西。這是我輸入錯誤「在System.Data.OleDb.ColumnBinding.ValueString()\ r \ n在System.Data.OleDb.OleDbDataReader.GetString(Int32序數)\ r \ n在WS.DAL.LinqSqlModelImporter.Import(String查詢)\\ WSModel \\ WS.DAL \\ LinqSqlModelImporter.cs:第23行\ r \ n位於\\ WSModel \\ Default.aspx.cs中的WSModel._Default.btnUpload_Click(對象發件人,EventArgs e):line 35「 – niceoneishere 2012-07-10 19:15:31