Using Async Await keywords with Dapper

2019-03-08 14:58发布

问题:

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 ?

回答1:

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



回答2:

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