我的sql是:
select (select count(*) from TblRMember where sex=1) male,
(select count(*) from TblRMember where sex=2) female,
(select count(*) from TblRMember where sex=0) unkown
我希望Dapper.Net像这样返回一个Dictinary:
Keys:male,female,nukown
Value:10,30,50
我已经看到如何使用Dapper Dot Net从数据库结果映射到Dictionary对象? ,但那不行!
如何使用ToDictionary或其他方式实现我想要的
var myDictionary = sqlConnection.Query(strSql).ToDictionary(??);
谢谢!
首先将您的查询更改为单个查询:
select case when sex = 1 then 'male'
when sex = 2 then 'female'
when sex = 0 then 'unknown'
end as sex, count(*) as cnt
from TblRMember
group by sex
因为我看到sex
是数字的,所以你要么必须通过名字(性别名?)来选择,或者在你的代码中改变它。之后:
var myDictionary = sqlConnection.Query(strSql)
.ToDictionary(x => x.sex.ToString(), x => (int)x.cnt);
string strSql = "SELECT DISTINCT TableID AS [Key],TableName AS [Value] FROM dbo.TS_TStuctMaster";
Dictionary<string,string> dicts = sqlConnection.Query<KeyValuePair<string,string>>(strSql).ToDictionary(pair => pair.Key, pair => pair.Value);
您可以使用别名和强类型。
别名是关键点,它与KeyValuePair类型Key和Value的属性相匹配。
它在强类型下运行并且运行良好。
我不喜欢动态类型。它在某些情况下会带来灾难。而且,装箱和拆箱会带来性能损失。