Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 7 Async collections

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.

like image 791
Fab Avatar asked Jan 22 '16 18:01

Fab


1 Answers

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();
        }
    }
}
like image 157
Shaun Luttin Avatar answered Dec 05 '22 11:12

Shaun Luttin