Reputation: 23
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
Upvotes: 1
Views: 798
Reputation: 707
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();
Upvotes: 1
Reputation: 236188
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).
Upvotes: 2