1. 应用查询方法并获取动静类型:
dynamic account = conn.Query<dynamic>(@"
SELECT Name, Address, Country
FROM Account
WHERE Id = @Id", new {Id = Id}).FirstOrDefault();
Console.WriteLine(account.Name);
Console.WriteLine(account.Address);
Console.WriteLine(account.Country);
如您所见,您取得了一个动静对象,并且您能够拜访其属性,只有它们在查问语句中定义良好。
如果你省略 .FirstOrDefault()
你会失去一个IEnumerable<dynamic>
,你能够用它做任何你想做的事件。
2. 应用作为 C# 7.0 的一部分增加的元组类型
var users = dbConnection
.Query<(Guid id, string username)>("SELECT id, username From users")
.AsList();
3. 将每一行转换为IDictionary<string, object>
,通过键获取查问值
IEnumerable<dynamic> query = db.Query<dynamic>("SELECT id, username FROM users");
foreach (var rows in query)
{
var fields = rows as IDictionary<string, object>;
var id = fields["id"];
var username = fields["username"];
}