Using Async Await keywords with Dapper

走远了吗. 提交于 2019-12-03 04:14:14

问题


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



回答3:


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();


来源:https://stackoverflow.com/questions/25833426/using-async-await-keywords-with-dapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!