SqlDataReader错误,从字符转换

时间:2016-08-17 21:18:09

标签: c# sql sql-server

我收到错误

  

从字符串转换为唯一标识符时转换失败。

我甚至没有任何日期转换,所以我在这里很丢失。

我正在使用参数化查询并添加来自数据视图的2个值。在这种情况下,如果我调试并检查日期的值,我会以这种格式{8/17/2016 9:08:44 PM}

获取它
string query = @"SELECT TOP 1 
                     SensorValue,
                     ActivityDateTime,
                     (Select TimeAlert from Vehicle_config 
                      where VehicleID = '@guid') as TimeAlert,
                     (Select DistanceAlert from Vehicle_config 
                      where VehicleID = '@guid') as DistanceAlert,
                     (Select TimeInterval from Vehicle_config 
                      where VehicleID = '@guid') as TimeInterval,
                     (Select DistanceInterval from Vehicle_config 
                      where VehicleID = '@guid') as DistanceInterval,
                     (Select AlertFlag from Vehicle_config 
                      where VehicleID = '@guid') as AlertFlag, 
                     (Select Litros from Vehicle_config 
                      where VehicleID = '@guid') as Litros
                 FROM 
                     navman_Fuel_activity 
                 WHERE 
                     ActivityDateTime < DATEADD(MI, -5, @date) 
                     AND VehicleId = '@guid' 
                 ORDER BY ActivityDateTime DESC;";

using (SqlConnection sqlConn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
    cmd.Parameters.AddWithValue("date", (DateTime)row["ActivityDateTime"]);
    cmd.Parameters.AddWithValue("guid",(Guid)row["VehicleID"]);

    sqlConn.Open();  

    using (var reader = cmd.ExecuteReader())
    {
        if (reader.Read()) // here is where I get the error

1 个答案:

答案 0 :(得分:1)

我相信失败发生在这条线上

cmd.Parameters.AddWithValue("guid",(Guid)row["VehicleID"]);

我认为你需要这样做而不是演员

cmd.Parameters.AddWithValue("guid",new Guid(row["VehicleID"]));