这是我的第二篇文章。在从我的第一篇文章中学习使用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