【问题标题】:CS1061 IOrderedEnumerable<TEntity>' does not contain a definition for 'ToListAsync' EF Core 6CS1061 IOrderedEnumerable<TEntity>' 不包含 'ToListAsync' EF Core 6 的定义
【发布时间】:2021-11-25 11:00:10
【问题描述】:

在 EF Core 6 上的 EntityFrameWorkCore 中是否已弃用 ToListAsync?

如果我使用 ToList() 方法,它可以工作,但如果我添加 ToListAsync,我会收到以下错误:

“IOrderedEnumerable”不包含“ToListAsync”的定义,并且找不到接受“IOrderedEnumerable”类型的第一个参数的可访问扩展方法“ToListAsync”(您是否缺少 using 指令或程序集引用?

代码示例:

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

namespace RainbowOF.Repositories.Common
{
    public class AppRepository<TEntity> : IAppRepository<TEntity> where TEntity : class
    {
        #region Privates
        private ApplicationDbContext _Context { get; set; }  // = null;
        private DbSet<TEntity> _Table = null;
        private ILoggerManager _Logger { get; }
        private IAppUnitOfWork _AppUnitOfWork { get; set; }
        #endregion
        #region Initialise
        public AppRepository(ApplicationDbContext dbContext, ILoggerManager logger, IAppUnitOfWork unitOfWork)
        {
            _Context = dbContext;
            _Table = dbContext.Set<TEntity>();
            _Logger = logger;
            _AppUnitOfWork = unitOfWork;
        }
        #endregion

        public IEnumerable<TEntity> GetAllOrderBy(Func<TEntity, object> orderByExpression, bool sortDesc = false)
        {
            _Logger.LogDebug($"Getting all records in Table of type: {typeof(TEntity)} order by {orderByExpression}");
            if (_AppUnitOfWork.DBTransactionIsStillRunning())
                _Logger.LogDebug("Second transaction started before current transaction completed!");
            try
            {
                var _result = sortDesc 
                    ? _Table.OrderByDescending(orderByExpression).ToList() 
                    : _Table.OrderBy(orderByExpression).ToList();
                return _result;
            }
            catch (Exception ex)
            {
                _AppUnitOfWork.LogAndSetErrorMessage($"!!!Error Getting all (async): {ex.Message} - Inner Exception {ex.InnerException}");
#if DebugMode
                throw;     // #Debug?
#endif
            }
            return null;
        }

        public async Task<IEnumerable<TEntity>> GetAllAsync()
        {
            _Logger.LogDebug($"Getting all records (async) in Table of type: {typeof(TEntity)}");
            if (_AppUnitOfWork.DBTransactionIsStillRunning())
                _Logger.LogDebug("Second transaction started before current transaction completed!");
            try
            {
                var _result =  await _Table.ToListAsync();
                return _result;
            }
            catch (Exception ex)
            {
                _AppUnitOfWork.LogAndSetErrorMessage($"!!!Error Getting all (async): {ex.Message} - Inner Exception {ex.InnerException}");
#if DebugMode
                throw;     // #Debug?
#endif
            }
            return null;
        }

//--> the above works fine, below gives the error.


        public async Task<IEnumerable<TEntity>> GetAllOrderByAsync(Func<TEntity, object> orderByExpression, bool sortDesc = false)
        {
            _Logger.LogDebug($"Getting all records (async) in Table of type: {typeof(TEntity)} order by {orderByExpression}");
            if (_AppUnitOfWork.DBTransactionIsStillRunning())
                _Logger.LogDebug("Second transaction started before current transaction completed!");
            try
            {
                var _result = sortDesc 
                    ? await _Table.OrderByDescending(orderByExpression).ToListAsync() 
                    : await _Table.OrderBy(orderByExpression).ToListAsync();
                return _result;
            }
            catch (Exception ex)
            {
                _AppUnitOfWork.LogAndSetErrorMessage($"!!!Error Getting all (async) order by: {ex.Message} - Inner Exception {ex.InnerException}");
#if DebugMode
                throw;     // #Debug?
#endif
            }
            return null;
        }

我已经尝试在上面添加。

我谷歌和一些票说在 6 中添加了 Async,有些人建议添加“使用 System.Data.Entity;”到用途。 如果我使用 System.Data.Entity 添加;然后那个错误消失了,但后来我与 EntityFrameworkCore 发生冲突。

项目已在 VS2022 中升级到 .net 6。它在.net 5中工作

也许我对技术感到困惑。

【问题讨论】:

  • 通过使用该 anti 模式,您破坏了 EF Core。所有这些代码只不过是 EF Core 和 LINQ 已经在做的事情,只是它不起作用。 DbContext已经是一个多实体 Unito-of-Work,DbSet已经是一个单实体存储库。实体,而不是表。不要急于“修复”假设的问题,直到您了解是否有任何需要修复的地方
  • 这段代码有几个问题,但导致错误的一个是 LINQ 使用表达式,而不是 lambda。 GetAllAsync 方法虽然没用 - 没有人想将整个表加载到内存中,尤其是在 EF Core 时。服务器查询和过滤数据的速度是任何客户端的数千倍。
  • 另一个非常严重的问题:DBTransactionIsStillRunning 表示 UoW 实际上已损坏。 EF Core 不需要数据库事务,因为 DbContext已经是一个工作单元。当使用SaveChanges 时,所有更改都会自动缓存和持久化。如果您必须使用数据库事务,则出现严重错误。您是否在每个InsertUpdate 之后调用SaveChanges?这是双重破坏,因为 Insert 将应用 任何 挂起的更改,包括删除和更新。
  • @PanagiotisKanavos 对此表示感谢。我是自学成才的,这表明了。我正在使用存储库来允许具有相同接口的不同实现。我阅读了大量关于使用 Repo 层的利弊的文章,在 .net 网站和 Pragim Tech 上完成教程后,我觉得这是最常见的解决方案。我添加了 DBTransaction 检查以尝试捕获代码中的任何异步错误。这样我就可以知道哪些电话有问题。大概可以去掉。目前 GetAllAsync 用于小型下拉列表,这就是我需要 order by 的原因。

标签: c# entity-framework-core .net-6.0 visual-studio-2022


【解决方案1】:

接受FuncOrderBy&lt;TSource,TKey&gt;(IEnumerable&lt;TSource&gt;, Func&lt;TSource,TKey&gt;) 是为IEnumerable 定义的方法,它确实具有ToList 的异步版本。您需要为IQueryable 定义的OrderBy&lt;TSource,TKey&gt;(IQueryable&lt;TSource&gt;, Expression&lt;Func&lt;TSource,TKey&gt;&gt;)),它使用ToListAsync 扩展(您还希望它因为IQueryable 重载实际上被转换为SQL,而IEnumerable 将获取所有数据到客户端并排序它在那里)。因此,更改您的方法签名以接受 func (Expression&lt;Func&lt;TEntity, object&gt;&gt;) 的表达式,而不仅仅是 func:

public async Task<IEnumerable<TEntity>> GetAllOrderByAsync(Expression<Func<TEntity, object>> orderByExpression, bool sortDesc = false)
{
    ...
}

额外信息:

【讨论】:

  • 谢谢你,我有点困惑,因为当我在 none async 上使用 Expression 时它失败了。我很难用 linq 表达式调用函数。我已经让 repo 中的例程正常工作,只是在后面的代码中努力使用它。它给我带来了 TKey 的问题,我不知道如何使用它。感谢您的帮助,我非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
  • 2017-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
  • 2023-03-20
相关资源
最近更新 更多