1

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;
 }
1

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

4 Comments

thank you.. I did this and it seems to be cmpiling correctly : var result = await db.QueryAsync<Event>("[sp_get_published_events]", null, commandTimeout: 60, commandType: CommandType.StoredProcedure); return result.AsList<Event>();
result needs a using
@Charlieface: In the question there's a using on the first line. That should cover this solution as well.
I don't think that makes any difference, that's for the connection not the reader. What does make a difference is whether it's a buffered command, which in this case it is (it's the default). See source code github.com/DapperLib/Dapper/blob/… Still probably best practice to have a using, it's not like it costs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.