35

I want to use a micro-orm and decided to go with Dapper.

But can't seem to find any mentions of it supporting the new async/await syntax. Async queries are important for me.

Can someone provide a code example of an async query being made with Dapper using the await keyword ?

Yaron Levi
  • 12,535
  • 16
  • 69
  • 118
  • 1
    possible duplicate of [What .Net orms or MicroOrms support async operations and PostgreSql](http://stackoverflow.com/questions/12343284/what-net-orms-or-microorms-support-async-operations-and-postgresql) – i3arnon Sep 14 '14 at 12:59

3 Answers3

46

Dapper when targeting .NET 4.5 has full support for TPL usage, via the methods ending in *Async - QueryAsync etc. Specifically, the .NET 4.5 build includes this extra set of methods

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    Great, this is what I was looking for. Do you have where can I find some code examples that use these methods ? – Yaron Levi Sep 14 '14 at 14:30
  • @Yaron they are basically the same as non-async - just add `await` at the start and `Async` at the end... Unless you need cancellation tokens, in which case you need to use a different API until the next build – Marc Gravell Sep 14 '14 at 14:37
35

Here's a sample Yaron

 public async Task<List<Artist>> GetAllAsync()
    {
        using (
            SqlConnection conn =
                new SqlConnection(Conn.String))
        {
            await conn.OpenAsync();

            using (var multi = await conn.QueryMultipleAsync(StoredProcs.Artists.GetAll, commandType: CommandType.StoredProcedure))
            {
                var Artists = multi.Read<Artist, AlbumArtist, Artist>((artist, albumArtist) =>
                {
                    artist.albumArtist = albumArtist;
                    return artist;
                }).ToList();

                var albums = multi.Read<Album, AlbumArtist, Album>(
                (album, albumArtist, album) =>
                {
                    album.albumArtist = album;
                    return albums;
                }).ToList();


                conn.Close();

                return Artists;
            }
        }
    }
Salman Syed
  • 568
  • 5
  • 9
  • 3
    Is the await conn.OopenAsync() required? I thought it opened the connection automatically – niico Jun 26 '20 at 17:12
1

Here are some examples.

Examples for Dapper - Async calls

However, this is not awaitable:

var results = await Connection.QueryAsync<T>(sql).Result.ToArray();

You have to write something like this:

var results = await Connection.QueryAsync<T>(sql);
return results.ToArray();
Gregor Jovan
  • 47
  • 1
  • 6