无法使用异步从 Type ICollection 转换为 List
Can't convert from Type ICollection to List with async
我在服务中有以下代码:
var countriesTask = countryIds != null && countryIds.Any()
? this.dataContext.Countries.Where(c => countryIds.Contains(c.CountryId)).ToListAsync()
: Task.FromResult(new List<Country>());
var countries = await countriesTask;
我想通过创建 RepositoryBase 来重构依赖 Datacontext class:
IRepositoryBase:
Task<ICollection<T>> FindAllAsync(Expression<Func<T, bool>> match);
RepositoryBase:
public virtual async Task<ICollection<T>> FindAllAsync(Expression<Func<T, bool>> match)
{
return await this.DbContext.Set<T>().Where(match).ToListAsync();
}
然后将上面的重构为:
var countriesTask = countryIds != null && countryIds.Any()
? this.countryRepository.FindAllAsync(c => countryIds.Contains(c.CountryId))
: Task.FromResult(new List<Country>());
var countries = await countriesTask;
我收到类型转换错误(无法从 Type ICollection Country 转换为 Type List Country,今天早上我的大脑不工作。我知道可能是 ToListAsync 引起了问题,但每个当我改变某些东西时,其他东西坏了!我该怎么办
在我看来你只需要这样做:
var countriesTask =
countryIds != null && countryIds.Any()
? this.countryRepository.FindAllAsync(c => countryIds.Contains(c.CountryId))
: Task.FromResult<ICollection<Country>>(new List<Country>());
基本上?:
两边的运算符需要return相同的类型。您的代码试图 return Task<ICollection<Country>>
& Task<List<Country>>
。通过使 return Task<ICollection<Country>>
它应该可以正常工作。
我在服务中有以下代码:
var countriesTask = countryIds != null && countryIds.Any()
? this.dataContext.Countries.Where(c => countryIds.Contains(c.CountryId)).ToListAsync()
: Task.FromResult(new List<Country>());
var countries = await countriesTask;
我想通过创建 RepositoryBase 来重构依赖 Datacontext class:
IRepositoryBase:
Task<ICollection<T>> FindAllAsync(Expression<Func<T, bool>> match);
RepositoryBase:
public virtual async Task<ICollection<T>> FindAllAsync(Expression<Func<T, bool>> match)
{
return await this.DbContext.Set<T>().Where(match).ToListAsync();
}
然后将上面的重构为:
var countriesTask = countryIds != null && countryIds.Any()
? this.countryRepository.FindAllAsync(c => countryIds.Contains(c.CountryId))
: Task.FromResult(new List<Country>());
var countries = await countriesTask;
我收到类型转换错误(无法从 Type ICollection Country 转换为 Type List Country,今天早上我的大脑不工作。我知道可能是 ToListAsync 引起了问题,但每个当我改变某些东西时,其他东西坏了!我该怎么办
在我看来你只需要这样做:
var countriesTask =
countryIds != null && countryIds.Any()
? this.countryRepository.FindAllAsync(c => countryIds.Contains(c.CountryId))
: Task.FromResult<ICollection<Country>>(new List<Country>());
基本上?:
两边的运算符需要return相同的类型。您的代码试图 return Task<ICollection<Country>>
& Task<List<Country>>
。通过使 return Task<ICollection<Country>>
它应该可以正常工作。