Dapper : Mapper Query not getting values where as Dynamic Object Mapper Query does

c# dapper

Question

I am a beginner to dapper . I was going through the code and building samples . But I am having problems in retrieving data . My code is as follows

 Console.WriteLine("Reading Values");
            string readSatement = "select * from employee where Id=@Id ";
             IEnumerable<Employee> objEmp1 = con.Query<Employee>(readSatement,
                 new {
                     Id = empId
                 });

             var objEmp2 = con.Query(readSatement, new { Id = empId }); 

In this code objEmp2 retrieves values from db for the id passed . But objEmp1 gives null values for the attributes of the object .

Employee class is as below

 public  class Employee
    {

      public int EmpId { get; set; }
      public string EmpName { get; set; }
      public int EmpAge { get; set; }
    } 

Whats wrong with the code .

Accepted Answer

You need to ensure all your database columns either match the properties in your class you are using for the query or you return the columns with names that match. For example in your query above, I believe you might want to write it like:

select Id as EmpId, otherColumn as Propertyname, etc.. from employee
where Id = @Id



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