Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map to a Dictionary object from database results using Dapper Dot Net?

Tags:

c#

asp.net

dapper

If I have a simple query such as:

string sql = "SELECT UniqueString, ID  FROM Table"; 

and I want to map it to a dictionary object such as:

Dictionary<string, int> myDictionary = new Dictionary<string, int>();       

How would I do this with Dapper?

I assume it is something like:

myDictionary = conn.Query<string, int>(sql, new {  }).ToDictionary(); 

But can't figure out the proper syntax.

like image 784
jpshook Avatar asked Feb 08 '13 20:02

jpshook


People also ask

Does Dapper use SqlClient?

SqlClient and SqlConnection , but Dapper supports other databases that use the DbConnection abstraction. We also need a projection class representing the results of our SQL query.

Is Dapper A ORM?

Dapper is an object–relational mapping (ORM) product for the Microsoft . NET platform: it provides a framework for mapping an object-oriented domain model to a traditional relational database. Its purpose is to relieve the developer from a significant portion of relational data persistence-related programming tasks.

What is Micro ORM Dapper?

Dapper is an example of Micro ORM, in fact, it is called the King of Micro ORM because of its speed and ease of work. Dapper works in the following way – First, it creates an IDbConnection object and allows us to write queries to perform CRUD operations on the database.

How do I use Dapper in Visual Studio?

In Visual Studio, create a new console project, and in Solution Explorer right-click References and select Manage NuGet Package Manager and search for Dapper and using the NuGet Package Manager Console command for the Nugget Package Manager “install-package dapper”, and this will install Dapper into your project.


2 Answers

There's various ways already shown; personally I'd just use the non-generic api:

var dict = conn.Query(sql, args).ToDictionary(     row => (string)row.UniqueString,     row => (int)row.Id); 
like image 153
Marc Gravell Avatar answered Sep 16 '22 11:09

Marc Gravell


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.

like image 26
Allen.Cai Avatar answered Sep 19 '22 11:09

Allen.Cai