Wednesday, February 22, 2017

Unable to cast object of type 'DapperRow' to return Type

Aloha,
Given the following code which generates an exception "Unable to cast object of type 'DapperRow", the cause for this is that the return type of FirstOrDefault() dynamic.
public Customer FindById(int Id)
{
 return this._db.Query("SELECT * FROM Customer WHERE CustomerID=@Id", new { Id = Id }).FirstOrDefault();
}
In order to solve this error, you have several options. One is to use Query.<TReturn>() instead of Query() wherein you can explicity specify the type.
public Customer FindById(int Id)
{
 return this._db.Query<Customer>("SELECT * FROM Customer WHERE CustomerID=@Id", new { Id = Id }).FirstOrDefault();
}
Another option is to modify the code with issue, that is to store the result of the query in a dynamic variable and then assign the dynamic properties value to the class properties.
public Customer FindById(int Id)
{
 dynamic customerRecord = this._db.Query("SELECT * FROM Customer WHERE CustomerID=@Id", new { Id = Id }).FirstOrDefault();
 
 return new Customer()
 {
  CustomerID = Convert.ToInt32(customerRecord.CustomerID),
  Address = customerRecord.Address,
  City = customerRecord.City,
  CompanyName = customerRecord.CompanyName,
  CreditLimit = Convert.ToDecimal(customerRecord.CreditLimit),
  IntroDate = Convert.ToDateTime(customerRecord.IntroDate),
  State = customerRecord.State
 };
}

0 comments:

Post a Comment