Reputation: 5307
I have the following code in a service:
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;
I wanted to refactor out the dependency Datacontext by creating a RepositoryBase 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();
}
And then refactoring the above to:
var countriesTask = countryIds != null && countryIds.Any()
? this.countryRepository.FindAllAsync(c => countryIds.Contains(c.CountryId))
: Task.FromResult(new List<Country>());
var countries = await countriesTask;
I'm getting a type conversion error (Can't convert from Type ICollection Country to Type List Country and my brain isn't working this morning. I know there is a ToListAsync that's probably causing the problem, but each time I change something, something else breaks! What do I do
Upvotes: 2
Views: 2542
Reputation: 117084
It seems to me that you just need to do this:
var countriesTask =
countryIds != null && countryIds.Any()
? this.countryRepository.FindAllAsync(c => countryIds.Contains(c.CountryId))
: Task.FromResult<ICollection<Country>>(new List<Country>());
Basically both sides of the ?:
operator need to return the same type. Your code was trying to return Task<ICollection<Country>>
& Task<List<Country>>
. By making both return Task<ICollection<Country>>
it should work fine.
Upvotes: 4