Entity Framework 7 Async collections

entity-framework-core

Question

Where is ToListAsync() in Entity Framework 7. How do I return a collection or SingleOrDefault using async methods in EF 7.

 public async Task<IEnumerable<TodoItem>> GetAllAsync()
    {   
        //TODO: ToListAsync missing?         

        return await _context.Todos.ToAsyncEnumerable();
    }

This is returning an error does not contain definition for GetAwaiter? SaveChangesAsync is no problems.

Popular Answer

Microsoft.EntityFrameworkCore Namespace

The Microsoft.EntityFrameworkCore namespace includes the async extension methods. That namespace is in the Microsoft.EntityFrameworkCore package. Here is the source on GitHub and here are its async extension methods.

  • AnyAsync()
  • AllAsync()
  • CountAsync()
  • LongCountAsync()
  • FirstAsync()
  • FirstOrDefaultAsync()
  • LastAsync()
  • LastOrDefaultAsync()
  • SingleAsync()
  • SingleOrDefaultAsync()
  • MinAsync()
  • MaxAsync()
  • SumAsync()
  • AverageAsync()
  • ContainsAsync()
  • ToListAsync()
  • ToArrayAsync()
  • LoadAsync()
  • ToDictionaryAsync()
  • ForEachAsync()

Example Usage

project.json

"Microsoft.EntityFrameworkCore": "1.0.0",

ApplicationUserRepository.cs

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace MyApplication.Models {
    public class ApplicationUserRepository : IApplicationUserRepository
    {
        private ApplicationDbContext _dbContext;

        public ApplicationUserRepository(ApplicationDbContext dbContext) {
            _dbContext = dbContext;
        }

        public async Task<ApplicationUser> Find(Guid id)
        {
            return await _dbContext.Users.SingleAsync(u => u.Id == id);
        }

        public async Task<IEnumerable<ApplicationUser>> GetAll()
        {
            return await _dbContext.Users.ToListAsync();
        }
    }
}


Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why