我一直在将部分代码转换为异步方法。 我使用工作单元/仓储/服务设计模式,我的仓储代码如下:
public class Repository<T> : IDisposable, IRepository<T> where T : class
{
private readonly DbContext context;
private readonly DbSet<T> dbEntitySet;
public Repository(DbContext context)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
this.dbEntitySet = context.Set<T>();
}
public IQueryable<T> GetAll(params string[] includes)
{
IQueryable<T> query = this.dbEntitySet;
foreach (var include in includes)
query = query.Include(include);
return query;
}
public void Create(T model)
{
this.dbEntitySet.Add(model);
}
public void Update(T model)
{
this.context.Entry<T>(model).State = EntityState.Modified;
}
public void Remove(T model)
{
this.context.Entry<T>(model).State = EntityState.Deleted;
}
public void Dispose()
{
this.context.Dispose();
}
}
在这个类中,我想将我的GetAll方法变成异步的。我找到了一篇文章,其中提到了以下方法:
public async Task<List<T>> GetAllAsync()
{
return await this.dbEntitySet.ToListAsync();
}
这很好,但在将任何内容返回给用户之前,我需要添加string[] includes。因此,我决定也许应该不去改动Repository,而是专注于服务,所以我有了这个方法:
public IList<User> GetAllAsync(params string[] includes)
{
return this.Repository.GetAll(includes).ToList();
}
我试图将其更改为以下内容:
public async Task<List<User>> GetAllAsync(params string[] includes)
{
return await this.Repository.GetAll(includes).ToListAsync();
}
但是我遇到了一个错误:
错误 1:'System.Linq.IQueryable'不包含定义为'ToListAsync'的方法,也没有接受类型为'System.Linq.IQueryable'的第一个参数的扩展方法'ToListAsync'可以找到(您是否缺少使用指令或程序集引用?)
有人能指点我正确的方向吗?