使用异步编程键入转换错误

r3p*_*ica 1 c# asynchronous entity-framework

谁能告诉我为什么这不起作用?

我有一个看起来像这样的方法:

public virtual async Task<IList<User>> GetAll()
{
    return this.db.Users.Where(model => model.CompanyId.Equals(this.companyId, StringComparison.OrdinalIgnoreCase)).ToListAsync();
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译我的代码时,我得到一个错误说明:

错误10无法将类型'System.Threading.Tasks.Task>'隐式转换为'System.Collections.Generic.IList'.存在显式转换(您是否缺少演员?)C:\ Users\Jaymie\Documents\GitHub\Skipstone\Skipstone.Web\Repositories\UserRepository.cs 70 20 Skipstone.Web

但直接在它下面我有这个方法:

public Task<User> FindByIdAsync(string userId)
{
    return this.db.Users.Where(model => model.Id.Equals(userId, StringComparison.OrdinalIgnoreCase)).SingleOrDefaultAsync();
}
Run Code Online (Sandbox Code Playgroud)

哪个工作正常.

我想我看不到木头的树木所以需要别人的眼睛来帮助我:)

Jea*_*nal 13

这些ToListAsync方法返回一个Task<List<T>>对象,该对象转换为Task<List<User>>您案例中的对象,但您的方法的返回类型是Task<IList<User>>.

这里的问题是,协方差不支持TTask<T>.

因此,要么将方法的返回类型更改为Task<List<User>>,要么编写代码以自行进行转换:

return this.db.Users
    .Where(model => model.Id.Equals(userId, StringComparison.OrdinalIgnoreCase))
    .ToListAsync()
    .ContinueWith<IList<User>>(t => t.Result, TaskContinuationOptions.ExecuteSynchronously);
Run Code Online (Sandbox Code Playgroud)