Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper : reading into dictionary from readrer

Tags:

c#

dapper

my reader reads the contents from the stored procedure which has one of its 1st select statement as

 select id , name from FSubsystem

out of 10 select staments

and i declared the dictionary like below Dictionary SubsystemMApping = new Dictionary();

var reader = connection.QueryMultiple(...);

I need to read the fist select statement values to dictionary SubsystemMApping . id - to Key and name - to value

I tried doing it using reader.Read.Todictionary() but couldn't succeed . I am not very familier with Func & Action . dats the reason why i think i am not able to understand the 2 overloads of Todictionary properly.

Can anyone help ?

like image 868
Kuntady Nithesh Avatar asked Dec 01 '22 20:12

Kuntady Nithesh


2 Answers

For the generic API, Stan has already described it. The non-generic Read API means you can also bypass the POCO via dynamic:

var lookup = reader.Read().ToDictionary(x => (int)x.id, x => (string)x.name);

Basically, via "dynamic" it re-exposes the columns as virtual properties.

like image 132
Marc Gravell Avatar answered Dec 04 '22 11:12

Marc Gravell


Imagine you have a POCO that's returned to you. Something like

public class Item 
{
   public int Id { get; set;}
   public string Name { get; set;}
}

Now imagine you have an IEnumerable<Item> and the collection is populated (this is most likely what Dapper is returning).

To use the ToDictionary method, you have 2 important overloads.

var dictionary = itemList.ToDictionary( item => item.Id );

This returns a Dictionary<int,Item>. The key for the dictionary is each item.Id property.

The key/value overload:

var dictionary = itemList.ToDictionary( item => item.Id , item => item.Name );

This overload creates a Dictionary<int,string> using the specified item.Id for key and item.Name for value.

There are 2 more overloads that allow you to pass a custom comparer to be used when determining keys.

like image 42
Stan R. Avatar answered Dec 04 '22 09:12

Stan R.