Dapper: reading into a dictionary from readrer

my reader reads the contents of a stored procedure that has one of its 1st select statements as

select id , name from FSubsystem 

out of 10 select items

and I declared a dictionary as shown below SubsystemMApping Dictionary = new dictionary ();

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

I need to read the values โ€‹โ€‹of the fist selection expression in the SubsystemMApping dictionary. id - to the key and name - value

I tried to do this with reader.Read.Todictionary () but could not succeed. I am not very familier with Func and Action. dats the reason why I think I can not correctly understand 2 Todictionary overloads.

Can anyone help?

+4
source share
2 answers

Imagine you have a POCO that is back to you. Sort of

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

Now imagine that you have an IEnumerable<Item> and the collection is full (this is most likely what Dapper returns)

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

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

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

Key / Value Overload:

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

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

There are two more overloads that allow you to pass a custom resolver, which will be used when defining keys.

+8
source

For a generic API, Stan has already described it. A raw reading API means that you can also bypass POCO through dynamic:

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

Basically, through "dynamic", it re-opens the columns as virtual properties.

+8
source

All Articles