我一直在将一些代码转换为异步方法。 我有一个工作单元/存储库/服务设计模式,我的存储库如下所示:
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();
}
但是我得到一个错误:
Error 1 'System.Linq.IQueryable' does not contain a definition for 'ToListAsync' and no extension method 'ToListAsync' accepting a first argument of type 'System.Linq.IQueryable' could be found (are you missing a using directive or an assembly reference?)
有人能给我指出正确的方向吗?
最佳答案
正如@mostruash 所指出的,如果我将 using System.Data.Entity 放入我的类引用中,它会编译并正常工作。
关于c# - 异步 EntityFramework 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25754383/