System.InvalidCastException:"无法将类型为'System.Double'的对象强制转换为类型'System.Single'。



Hy, 我在网上收到此错误_obj。添加(新数据((... 这是我的代码

SqlCommand com = new SqlCommand("sp_get_a", con)
{
CommandType = CommandType.StoredProcedure
};
_obj = new List<n>();
con.Open();
SqlDataReader rdr = com.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
_obj.Add(new data() { Id = rdr.GetInt32(0), na = rdr.GetString(1), Al = rdr.GetString(2), Sc = rdr.GetFloat(3), So = rdr.GetInt32(4), Ta = rdr.GetInt32(5), Ai = rdr.GetInt32(6), Sh = rdr.GetInt32(7) });
}
}
else
{
throw new Exception("rdr don't have any rows");
}
con.Close();

我的存储过程

CREATE PROCEDURE sp_get_a

如 选择 id, na, al, sc, so, ta, ai, sh 从 x 我没有任何双精度值,最接近双精度的是 Sc(float(。所以我尝试了 Sc = Convert.ToSingle(rdr.GetFloat(3((. 我哪里做错了? 编辑 - 我的模型

public class n
{
public int Id { get; set; }
public string Na { get; set; }
public string Al { get; set; }
public float Sc { get; set; }
public int So { get; set; }
public int Ta { get; set; }
public int Ai { get; set; }
public int Sh { get; set; }
}

您需要将Sc的数据类型从float更改为double

SQL Serverreal

等效于 C#Single,SQL Serverfloat等效于 C#Double

你也应该考虑@jdweng这一点

相关内容

最新更新