简体   繁体   中英

How do I map class object with Dapper

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM