Dapper.net use query into the Dictionary

c# dapper

Question

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!

Accepted Answer

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);

Popular Answer

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.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why