Home > Mobile >  How do I map class object with Dapper
How do I map class object with Dapper

Time:10-06

I am currently mapping the database query output to a class object in the following. Is there anyway I can directly map it with out using foreach loop?

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Address { get; set; }
}


string select = "SELECT Id, Name, Address FROM emp where Id  = 100";

string dbConnection="Server = TestServer; userid = XXXX; password = YYYYY; database = TestDB; port = 1234";

Person person = new Person();

using (var connection = new MySqlConnection(dbConnection))
{
    var v = await connection.QueryAsync<Person>(select);
    if (v != null)
    {
        foreach (var res in v)
        {
            person.Id = res.Id;
            person.Name = res.Name;
            person.Address = res.Address;
        }
    }
}

CodePudding user response:

The code doesn't make logical sense as you are looping over a list of people & overwriting a single Person object with every new person being enumerated.

That aside, the result of await connection.QueryAsync<Person>(select); will be of type IEnumerable<Person>.

var v = await connection.QueryAsync<Person>(select);

is equal to:

IEnumerable<Person> = await connection.QueryAsync<Person>(select);

You already have a collection of Person objects mapped.

  • Related