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

问题描述 投票:0回答:1

嗨,我在_obj.Add(new data()...这是我的代码

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

AS选择ID,Na,Al,Sc,So,Ta,Ai,Sh来自x我没有任何double值,并且最接近double的是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; }
}
c#
1个回答
0
投票

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

SQL Server real等效于C#Single,SQL Server float等效于C#Double

而且您也应该考虑@jdweng点

© www.soinside.com 2019 - 2024. All rights reserved.