【问题标题】:Asynchronous EntityFramework operations异步 EntityFramework 操作
【发布时间】:2014-09-09 22:13:11
【问题描述】:

我一直在将一些代码转换为异步方法。 我有一个工作单元/存储库/服务设计模式,我的 存储库 看起来像这样:

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[] 包含。所以我决定也许我应该不理会 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”(您是否缺少使用指令还是程序集引用?)

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

【问题讨论】:

  • 根据msdn.microsoft.com/en-us/library/dn220258(v=vs.113).aspx,如果您是using System.Data.Entity 并且如果您确实使用的是EF6,则不可能出现该错误。再次检查 dll 版本以确保。
  • 我建议从你的所有项目中卸载/重新安装 EF6 NuGet 包(如果它是一个多项目的东西)。
  • 我这样做了,但我仍然遇到同样的问题:(
  • 我的立场是正确的;它已编译:D
  • 就我而言,我有类似的 AnyAsync() 但我无法在 Visual Studio 的帮助下解决它,支持将我链接到解决方案并感谢@mostruash

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


【解决方案1】:

正如@mostruash 所指出的,如果我将 using System.Data.Entity 放入我的类引用中,它可以编译并正常工作。

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2017-06-29
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多