Donate

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
 };
}

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations