实体框架7异步集合

时间:2016-01-22 18:04:12

标签: entity-framework-core

实体框架7中的ToListAsync()在哪里。如何在EF 7中使用异步方法返回集合或SingleOrDefault。

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

        return await _context.Todos.ToAsyncEnumerable();
    }

这是返回错误,不包含GetAwaiter的定义? SaveChangesAsync没问题。

2 个答案:

答案 0 :(得分:14)

Microsoft.EntityFrameworkCore命名空间

Microsoft.EntityFrameworkCore命名空间包含async扩展方法。该命名空间位于Microsoft.EntityFrameworkCore包中。这是the source on GitHub,这是async扩展方法。

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

使用示例

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

答案 1 :(得分:0)

ToListAsync()SingleOrDefaultAsync()以及Microsoft.Data.Entity包中的名称空间EntityFramework.Core中存在许多其他异步方法。