今天帮群友整理Dapper基础教程的时候手脚快了点,然后遇到了一个小问题,Dapper QueryMultiple 返回数据的问题
多个返回值用QueryMultiple ,这个大家都知道,如果不清楚的看下下面的文档:
这个是官方文档:
Multiple Results
Dapper allows you to process multiple result grids in a single query.
Example:
var sql =
@"
select * from Customers where CustomerId = @id
select * from Orders where CustomerId = @id
select * from Returns where CustomerId = @id"; using (var multi = connection.QueryMultiple(sql, new {id=selectedId})) { var customer = multi.Read<Customer>().Single(); var orders = multi.Read<Order>().ToList(); var returns = multi.Read<Return>().ToList(); ... }
按照文档来,为啥没数据呢,就ID有值?难道多表只能传一个参数,而且必须有关系???NONONO,如果这么多限制还叫Dapper吗??
给你3s找错误。。。。。
其实就是顺序弄颠倒了,园友可以当个经验==》Dapper QueryMultiple并不会帮我们识别多个返回值的顺序
Read获取的时候必须是按照上面返回表的顺序 (article,qqmodel,seotkd)
var articleList = multi.Read<Temp>();//类不见得一定得和表名相同
var QQModelList = multi.Read<QQModel>();
var SeoTKDList = multi.Read<SeoTKD>();
官方文档是这样写的,那我们能不能玩点其他的?就一定得定义一个类来获取对应的强类型吗?多返回值就不能动态获取吗???NONONO
直接
if (!multi.IsConsumed)
{
var articleList = multi.Read();
var QQModelList = multi.Read();
var SeoTKDList = multi.Read();
}
一样的效果
周日会有一篇文章详细说下Dapper的,现在得出省了。。。。立刻,马上。。。
附录:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
using
(SqlConnection conn =
new
SqlConnection(connStr))
{
string
sqlStr =
@"select Id,Title,Author from Article where Id = @Id
select * from QQModel where Name = @Name
select * from SeoTKD where Status = @Status"
;
conn.Open();
using
(
var
multi = conn.QueryMultiple(sqlStr,
new
{ Id = 11, Name =
"打代码"
, Status = 99 }))
{
//multi.IsConsumed reader的状态 ,true 是已经释放
if
(!multi.IsConsumed)
{
////强类型
////注意一个东西,Read获取的时候必须是按照上面返回表的顺序 (article,qqmodel,seotkd)
//var articleList = multi.Read<Temp>();//类不见得一定得和表名相同
//var QQModelList = multi.Read<QQModel>();
//var SeoTKDList = multi.Read<SeoTKD>();
////动态类型
var
articleList = multi.Read();
var
QQModelList = multi.Read();
var
SeoTKDList = multi.Read();
#region 输出
foreach
(
var
item
in
QQModelList)
{
Console.WriteLine(item.Id +
" "
+ item.Name +
" "
+ item.Count);
}
foreach
(
var
item
in
SeoTKDList)
{
Console.WriteLine(item.Id +
" | "
+ item.SeoKeywords);
}
foreach
(
var
item
in
articleList)
{
Console.WriteLine(item.Author);
}
#endregion
}
}
}
|
本文转自毒逆天博客园博客,原文链接:http://www.cnblogs.com/dunitian/p/5221058.html,如需转载请自行联系原作者