0
votes

I'm using Dapper for retrieve a result of my request SELECT.

 List<dynamic> results = connection.Query("SELECT id_fonction from liste_personnels_fonctions where id_personnel = @id_personnel", new { id_personnel }).ToList();

But sometimes I have 2 results. When I use .SingleOrDefault() I have an exception : "Sequence contains several elements" when I have more than one row returned. When I use FirstOrDefault I have only first row and I need both of them... So what can I do? I try with List<> and var[] to retrieve the results but it doesn't work.

Any ideas? Thanks.

1
SingleOrDefault throws an exception if there is more than 1. That is by design. if you want the first use FirstOrDefault. If you need (up to) two of them use Take(2).ToList(). If you need all use ToList(). - mjwills
Thanks you a lot! - Elddif
Hmm, but now I don't know how to retrieve this result into the List<int>. I have : List<dynamic> results = connection.Query("SELECT id_fonction from liste_personnels_fonctions where id_personnel = @id_personnel", new { id_personnel }).ToList(); List<int> fonctions = new List<int>(); foreach (dynamic r in results) { var func = (int)r?.func; fonctions.Add(func); } and an exception when I do var func = (int)r?.func; - Elddif
My result is : {{DapperRow, id_fonction = '10'}} and {{DapperRow, id_fonction = '8'}} and I need only List<int> {10, 8} (sorry I don't know how to explain - Elddif
Select(z => z.id_fonction).ToList() because id_fonction is the column name. - mjwills

1 Answers

1
votes

If you want just a list of Int then ask Dapper for that

List<int> results = connection.Query<int("SELECT id_fonction from liste_personnels_fonctions where id_personnel = @id_personnel", new { id_personnel }).ToList();