读书人

指定的转换无效。解决思路

发布时间: 2012-05-28 17:59:54 作者: rapoo

指定的转换无效。
public List< PetShop.Model.ItemInfo> GetItemById(string ItemId)

{

string sql = "select item.itemid, item.name, item.listprice, product.name, item.image, product.categoryid, product.productid from item inner join product on item.productid = product.productid where item.itemid = @itemid";
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ssa"].ConnectionString;


List<PetShop.Model.ItemInfo> list = new List<PetShop.Model.ItemInfo>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();

command.Parameters.Add("@itemid", SqlDbType.NVarChar).Value = ItemId;

SqlDataReader reader = command.ExecuteReader();



if (reader.Read())
{


PetShop.Model.ItemInfo item = new PetShop.Model.ItemInfo()
{
ItemId = reader.GetString(0),
Name = reader.GetString(1),
Quantity = reader.GetInt32(2),
ListPrice = reader.GetDecimal(3),
ProductName = reader.GetString(4),
Image = reader.GetString(5),
CategoryId = reader.GetString(6),
ProductId = reader.GetString(7)
};

list.Add(item);

}
return list;

}





//////////////////////////////////////以下是报错的行/////////
PetShop.Model.ItemInfo item = new PetShop.Model.ItemInfo()
{
ItemId = reader.GetString(0),
Name = reader.GetString(1),
Quantity = reader.GetInt32(2),
ListPrice = reader.GetDecimal(3),
ProductName = reader.GetString(4),
Image = reader.GetString(5),
CategoryId = reader.GetString(6),
ProductId = reader.GetString(7)

[解决办法]
还有可能是视图的结构与你的model结构不同
主要原因就是数据类型错误 一般是int和字符串类型

读书人网 >.NET

热点推荐