r3plica
r3plica

Reputation: 13397

Asynchronous EntityFramework operations

I have been converting some code into async methods. I have a unit of work/repository/service design pattern and my Repository looks like this:

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();
    }
}

In this class, I want to make my GetAll method asynchronous. I found an article that had this as a method:

public async Task<List<T>> GetAllAsync()
{
    return await this.dbEntitySet.ToListAsync();
}

this is all fine and dandy, but I need the string[] includes to be added before I return anything to the user. So I have decided that perhaps I should leave the Repository alone and focus on the service, so I have this method:

public IList<User> GetAllAsync(params string[] includes)
{
    return this.Repository.GetAll(includes).ToList();
}

which I have tried to change to this:

public async Task<List<User>> GetAllAsync(params string[] includes)
{
    return await this.Repository.GetAll(includes).ToListAsync();
}

but I get an error:

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?)

Could someone point me in the right direction?

Upvotes: 4

Views: 4355

Answers (1)

r3plica
r3plica

Reputation: 13397

As @mostruash has pointed out, if I put the using System.Data.Entity into my class references, it compiles and works fine.

Upvotes: 6

Related Questions