异步EntityFramework操作

4

我一直在将部分代码转换为异步方法。 我使用工作单元/仓储/服务设计模式,我的仓储代码如下:

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'可以找到(您是否缺少使用指令或程序集引用?)

有人能指点我正确的方向吗?


2
根据http://msdn.microsoft.com/en-us/library/dn220258(v=vs.113).aspx的说法,如果你正在使用EF6并且使用了`using System.Data.Entity`,那么不可能出现该错误。请再次检查dll版本以确保。 - mostruash
1
我建议您从所有项目中卸载/重新安装EF6 NuGet包(如果这是一个多项目的事情)。 - mostruash
我已经这样做了,但仍然遇到相同的问题 :( - r3plica
我改正了,它已经编译成功 :D - r3plica
对于我的情况,我有类似于AnyAsync()的问题,但是我无法在Visual Studio的帮助下解决它,请为我提供解决方案点赞,感谢@mostruash。 - V-SHY
1个回答

6
正如@mostruash所指出的那样,如果我将using System.Data.Entity放入我的类引用中,它就能够编译和正常工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接