Dapper : reading into dictionary from readrer

c# dapper

Question

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 ?

Accepted Answer

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 a 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 pass a custom comparer to be used when determining keys.


Expert Answer

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.




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