Learning to use Dapper: throws Invalid cast error

c# dapper

Question

VS2013 c# windows form. I am learning Dapper and this is my 1st shot at it: I have a simple class:

 public class R
 {
     public int RID   { get; set; }
     public int RType { get; set; }
     public string CC { get; set; }
     public string RI { get; set; }
     .
     .
     .
}

    private void _setR(string rID)
    {            
        int r_ID = Convert.ToInt16(requestID);
        MY_R = new R();

        SqlConnection c = new SqlConnection(Connection string);
        c.Open();
        var v= c.Query<R>("select RID, RType, CC, RI, .,.,., " +
                                          "from Db_View_R where RID=@r_ID", 
                                          new { @r_ID = r_ID }) ;
        c.Close();            
        MY_R = (R)v ; <--------- Invalid cast error here
    }

The query is simple: a few columns from a view. Returns only 1 row. Not sure what am I missing here. Thanks in advance

Accepted Answer

Extension method Query<T> returns IEnumerable<T>. So you definitely can't assign value of type IEnumerable<T> to variable of type T. You should take only one item from sequence:

MY_R = v.FirstOrDefault(); // or First, Single, SingleOrDefault

Actually with improved naming your code should look like:

var sql = "SELECT RID, RType, CC, RI FROM Db_View_R where RID = @id";

using(var conn = new SqlConnection(ConnectionString))
{
     MY_R = conn.Query<R>(sql, new { id = Convert.ToInt16(requestID) })
                .FirstOrDefault();
}

I still don't like names like R (it probably should be Request) but its already much more readable and safe (you should wrap connection usage in using statement).


Popular Answer

use SingleOrDefault()

var v= c.Query<R>("select RID, RType, CC, RI, .,.,., " +
                                          "from Db_View_R where RID=@r_ID", 
                                          new { @r_ID = r_ID }).SingleOrDefault();



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why