Search code examples
c#.net-coreormdapper

Dapper - How to return record as Custom object type?


I am trying to run a query using Dapper and map data to a custom class object Emp.

public class Emp
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string LastName { get; set; }
}

My dapper execution code:

    string connectionString = @"Server = myserver; userid = test; password = test; database = testdb; port = 3306; Convert Zero Datetime=True";

    using (var connection = new MySqlConnection(connectionString))
    {
        string sql = "SELECT * FROM EMP where empno = 1010;
        List<Emp> empList = connection.Query<Emp>(sql: sql).ToList();
    }

The above code is working fine. I tried the following,

    Emp emp = (Emp)connection.Query<Emp>(sql:sql);

Error: Unable to cast object of type System.Collections.Genetic List[Emp] to type Emp

I can get the record as below and its working.

    Emp emp1 = empList[0];

Is there anyway I can get the query return type as Emp?


Solution

  • The method Query returns a list of records (rows). To get only one result you need to use QuerySingle or QuerySingleOrDefault

    Emp emp = connection.QuerySingleOrDefault<Emp>(query);