Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Query multiple results in Dapper asychronously

I am trying to fix an issue with an existing code and not sure if this approach is correct or not as I have not worked with dapper before. I am trying to return a list of objects using a stored procedure.

The code below compiles but I am not sure if this is the correct way to return multiple rows or not. Is there anything that just returns to list rather than me looping through and constructing list and then returning?

public async Task<List<Event>> GetEventsAsync()
{
   await using SqlConnection db = new(this.settings.ConnectionString);
       
   List<Event> events = new List<Event>();

   var eventsMarkedPublished =  await db.QueryAsync<Event>("[sp_get_published_events]", null, commandTimeout: 60, commandType: CommandType.StoredProcedure);

     foreach (var pubEvents in eventsMarkedPublished)
     {
        events.Add(pubEvents);
     }

     return events;
 }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can try to return List by ToList method directly.

return (await db.QueryAsync<Event>("[sp_get_published_events]", null, commandTimeout: 60, commandType: CommandType.StoredProcedure)).ToList();

or

var result = await db.QueryAsync<Event>("[sp_get_published_events]", null, commandTimeout: 60, commandType: CommandType.StoredProcedure);
return result.ToList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading