c# - 异步 EntityFramework 操作

标签 c# linq entity-framework asynchronous async-await

我一直在将一些代码转换为异步方法。 我有一个工作单元/存储库/服务设计模式,我的存储库如下所示:

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/

相关文章:

c# - 从泛型类型参数获取类的静态属性

c# - 如何在编译时注入(inject) C# 代码?

c# - C# 中的 LINQ。检查一个列表是否包含另一个列表中的元素

sql-server - Entity Framework CTP5 - 如何调用存储过程?

sql - 存储过程始终返回 -1(asp.net MVC、Entity、SQL)

c# - 右键单击文件执行两个任务,c#

c# - 丰富枚举 - 可能吗?

entity-framework - 在web.config中定义 Entity Framework SetInitializer

c# - 使用来自 qrouped 数据的 linq 的条件平均不返回任何内容

c# - 带有大量嵌套列表的列表上的 LINQ