C#Automapper,无法隐式转换为Task返回类型

Hen*_*rix 0 c# automapper

我知道它看起来很简单,但我花了很多时间在这上面.

不知怎的,我无法成功返回列表...

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;

}
Run Code Online (Sandbox Code Playgroud)

在"返回列表;",它给了我错误:

无法隐式转换System.Collections.Generic.List<MyViewModel>System.Threading.Tasks.Task<System.Collections.Generic.List<MyViewModel>>

有任何想法吗?

Stu*_*tLC 6

您没有等待数据库调用的结果.因此,electionsTask<>DB调用返回的类型是数据库调用返回的DTO类型(即使您返回a Task,AutoMapper也无法映射结果).

您需要创建该方法async,然后等待DB调用的结果,然后将其传递给Automapper进行映射.

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我多么愚蠢.是的,我错过了'异步'......:D (2认同)