entity-framework-core - Entity Framework 7异步集合

标签 entity-framework-core

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

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

        return await _context.Todos.ToAsyncEnumerable();
    }

这返回一个错误,其中不包含GetAwaiter的定义? SaveChangesAsync没有问题。

最佳答案

Microsoft.EntityFrameworkCore命名空间
Microsoft.EntityFrameworkCore命名空间包括async扩展方法。该 namespace 在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();
            }
        }
    }
    

    关于entity-framework-core - Entity Framework 7异步集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34953189/

    相关文章:

    c# - 原始 SQL 查询和 Entity Framework Core

    c# - Linq Any() 抛出错误 : String was not recognized as a valid boolean

    c# - Entity Framework 6 的插入顺序由什么逻辑决定

    c# - 在 EF Core 中应用所有 IEntityTypeConfiguration 派生类

    c# - 如何使用 Entity Framework 扩展 BulkInsert 和 AllowDuplicateKeys

    sql-server - 如何编写 EF.Functions 扩展方法?

    c# - 不支持从 _ 到 _ 的关系,因为拥有的实体类型 _ 不能位于非所有权关系的主体端

    entity-framework - 什么是自有实体?何时以及为何在 Entity Framework Core 中使用拥有的实体?

    c# - .ThenInclude 用于 Entity Framework Core 2 中的子实体

    c# - 数据库操作预计影响 1 行,但实际影响 0 行