C# Automapper, Cannot implicitly convert for Task return type


I know it looks simple, but I have spent quite some time on this.

Somehow I could not return list successfully...

public Task<List<MyViewModel>> getGoodElections(long actionId)
{
    var elections = _DBsource.ElectionTable.Where(e => e.ActionId == actionId && e.Status == "OK").ToListAsync();
    List< MyViewModel > list = Mapper.Map<List<MyViewModel>>(elections);
    return list;

}

At "return list;", it's giving me error:

Cannot implicitly convert type 'System.Collections.Generic.List<MyViewModel>' to 'System.Threading.Tasks.Task<System.Collections.Generic.List<MyViewModel>>'

Any ideas?

- - Source

Answers

answered 5 mon ago StuartLC #1

You're not awaiting the result of your database call. As a consequence, the elections returned from the DB call is of type Task<> of whatever the DTO type is that your DB call returns (i.e. even if you return a Task, AutoMapper won't be able to map the result anyway).

You need to make the method async, and then await the result of the DB call, before passing it off to Automapper to map.

public async Task<List<MyViewModel>> getGoodElections(long actionId)
{
    var elections = await _DBsource.ElectionTable
       .Where(e => e.ActionId == actionId && e.Status == "OK")
       .ToListAsync();
    var list = Mapper.Map<List<MyViewModel>>(elections);
    return list;
}

answered 5 mon ago pseabury #2

You haven't awaited the Task (ToListAsync), so you don't have a List<Election>. You should await the call to ToListAsync() and mark the method as async like below.

public async Task<List<MyViewModel>> getGoodElections(long actionId)
{
    var elections = await _DBsource.ElectionTable.Where(e => e.ActionId == actionId && e.Status == "OK").ToListAsync();
    List< MyViewModel > list = Mapper.Map<List<MyViewModel>>(elections);
    return list;

}

comments powered by Disqus