my sql is :
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
I want Dapper.Net to return a Dictinary like this:
Keys:male,female,nukown
Value:10,30,50
I have see How to map to a Dictionary object from database results using Dapper Dot Net? ,but that can not work!
How to use ToDictionary or other way to implement I want
var myDictionary = sqlConnection.Query(strSql).ToDictionary(??);
Thanks!
First change your query to be single one:
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
as I see sex
is numerical, so you either have to select by coumn with name (sexname?) or change it in your code. After that:
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);
You can use aliases and strong types.
Aliases are the key points, which match the attributes of KeyValuePair type Key and Value.
It works under strong typing and runs well.
I don't like dynamic type. It brings disaster in certain situations. Moreover, the boxing and unboxing brings performance loss.
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.