C#SQLite从DB获取实际值生成无效的强制转换异常

C#SQLite从DB获取实际值生成无效的强制转换异常,c#,sqlite,C#,Sqlite,我正在尝试使用C#从SQLiteDatabase获取实际值。 除了真正的价值之外,一切都很好 我使用以下代码从数据库中获取数据 // Building query... cmd.CommandText = "SELECT * " + "FROM ProductsPrice p " + "WHERE p.ProductId = @ProductId " + "ORDER BY Date DESC " + "LIMIT 1"; cmd.CommandType = Co

我正在尝试使用C#从SQLiteDatabase获取实际值。 除了真正的价值之外,一切都很好

我使用以下代码从数据库中获取数据

// Building query...
cmd.CommandText = "SELECT * " +
    "FROM ProductsPrice p " +
    "WHERE p.ProductId = @ProductId " +
    "ORDER BY Date DESC " +
    "LIMIT 1";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ProductId", ProductId);

// Execute query
using (SQLiteConnection conn = DatabaseService.getDbConnection())
using (cmd.Connection = conn)
{

    //Open Connection
    conn.Open();

    using (SQLiteDataReader dr = cmd.ExecuteReader())
        while (dr.Read())
        {
            //var x = dr.GetString(dr.GetOrdinal("NetPrice"));
            //var y = dr["GrossPrice"];
            //var x = dr.GetOrdinal("GrossPrice").GetType();

            price.Id = dr.GetInt32(dr.GetOrdinal("Id"));
            price.NetPrice = dr.GetDouble(dr.GetOrdinal("NetPrice"));
            price.GrossPrice = dr.GetDouble(dr.GetOrdinal("GrossPrice"));
            price.VAT = dr.GetDouble(dr.GetOrdinal("Vat"));
            price.AddedDate = dr.GetDateTime(dr.GetOrdinal("Date"));
        }

}
目标价格如下:

public int Id { get; set; }
public double NetPrice  { get; set; }
public double GrossPrice  { get; set; }
public double VAT  { get; set; }
public DateTime AddedDate { get; set; }
ID = INTEGER
NetPrice = REAL
GrossPrice = REAL
Vat = REAL
Date = datetime
数据库列如下所示:

public int Id { get; set; }
public double NetPrice  { get; set; }
public double GrossPrice  { get; set; }
public double VAT  { get; set; }
public DateTime AddedDate { get; set; }
ID = INTEGER
NetPrice = REAL
GrossPrice = REAL
Vat = REAL
Date = datetime
当我得到净价格时,这是有效的,因为值是2。但是当我得到GrossPrice时,我得到一个无效的强制转换异常,因为这个值是2.42。 我做错了什么

如果我检查GrossPrice的GetType(),它是一个Int32。但如果值为2.42,这是不可能的。 如果我使用
price.GrossPrice=Convert.ToDouble(dr[“GrossPrice”])
我会得到结果2(没有.42)。 如果我将SQLite DB列类型更改为Double或Float。它不会改变任何事情。
我没有主意了……

什么是“价格”变量?如果是您的自定义类,请在您的问题中也包括该类。我认为您在“price”对象的类定义中错误地定义了GrossPrice(int)。如果属性类型错误,这将是编译错误,而不是运行时
InvalidCastException
。您是对的,我的错误。我不知道这是否有用,但我有一些使用SQLite数据库的项目,我在.NET中将“decimal”定义为SQLite数据库中的类型和浮点。它工作正常。虽然我使用的是EF,所以我不知道在DataReader上调用哪个方法(可能是GetFloat)?我试过你的建议。我将DB列更改为float,并使用GetFloat()获取数据。但我还是得到了残疾人的权利。。这是stacktrace:System.InvalidCastException:指定的强制转换无效。在System.Data.SQLite.SQLiteDataReader.VerifyType(Int32 i,DbType typ)和System.Data.SQLite.SQLiteDataReader.GetFloat(Int32 i)中,我尝试使用十进制而不是双精度。这会产生不同的结果。现在我得到一个“FormatExeption:输入字符串的格式不正确”。另外,当我直接将GetDecimal读入变量时,它仍然会给出该异常。