如何使用 Dapper 映射 class 对象
How do I map class object with Dapper
我目前正在将数据库查询输出映射到下面的 class 对象。无论如何我可以直接映射它而不使用 foreach 循环?
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;
}
}
}
该代码没有逻辑意义,因为您要遍历人员列表并覆盖单个 Person
对象并枚举每个新人员。
除此之外,await connection.QueryAsync<Person>(select);
的结果将是 IEnumerable<Person>
.
类型
var v = await connection.QueryAsync<Person>(select);
等于:
IEnumerable<Person> = await connection.QueryAsync<Person>(select);
您已经映射了 Person
个对象的集合。
我目前正在将数据库查询输出映射到下面的 class 对象。无论如何我可以直接映射它而不使用 foreach 循环?
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;
}
}
}
该代码没有逻辑意义,因为您要遍历人员列表并覆盖单个 Person
对象并枚举每个新人员。
除此之外,await connection.QueryAsync<Person>(select);
的结果将是 IEnumerable<Person>
.
var v = await connection.QueryAsync<Person>(select);
等于:
IEnumerable<Person> = await connection.QueryAsync<Person>(select);
您已经映射了 Person
个对象的集合。