【问题标题】:Entity Framework Core - This may indicate either a bug or a limitation in EF CoreEntity Framework Core - 这可能表示 EF Core 中的错误或限制
【发布时间】:2020-06-13 21:00:37
【问题描述】:

我想从用户那里加载最新的私人聊天消息。

我加载最新消息的代码

 public async Task<List<UserChatMessage>> GetUserPrivateChatMessagesAsync(string userId, string userChatPartnerId, int limit, int skip, CancellationToken cancellationToken) {
      cancellationToken.ThrowIfCancellationRequested();
      if (userId == null) throw new ArgumentNullException(nameof(userId));
      if (userChatPartnerId == null) throw new ArgumentNullException(nameof(userChatPartnerId));

      return await this.Context.Messages
        .OrderBy(d => d.CreatedDate)
        .AsNoTracking()
        .Include(p => p.UserChatPartner)
        .Where(u => u.UserId == userId && u.UserChatPartnerId == userChatPartnerId || u.UserChatPartnerId == userId && u.UserId == userChatPartnerId)
        .TakeLast(limit)
        .Skip(skip)
        .ToListAsync(cancellationToken);
    }

以下代码抛出此错误:

System.InvalidOperationException: Processing of the LINQ expression 'DbSet<UserChatMessage>
    .OrderBy(d => d.CreatedDate)
    .Include(p => p.UserChatPartner)
    .Where(u => u.UserId == __userId_0 && u.UserChatPartnerId == __userChatPartnerId_1 || u.UserChatPartnerId == __userId_0 && u.UserId == __userChatPartnerId_1)
    .TakeLast(__p_2)' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.

我将 .Take 更改为 .TakeLast,现在我得到了描述的错误。

UserChatMessage 的数据库结构
我还尝试将 ToListAsync 更改为 AsEnumerable ,但没​​有成功。
我希望有人理解错误并可以帮助我。

提前致谢。
提莫

【问题讨论】:

  • “我改变了......现在我得到了描述的错误”使问题变得不清楚。哪个代码变体会产生哪个错误?

标签: asp.net linq entity-framework-core


【解决方案1】:

该错误意味着您遇到了当前的 EF Core 错误或限制。

我将.Take 更改为.TakeLast,现在我得到了描述的错误。

所以你知道是什么导致了这个问题。通常避免名称中包含Last 的LINQ 方法(如LastLastOrDefaultTakeLast)——这些在SQL 世界中没有直接等效项,因此有更大的机会遇到错误/限制(或者只是不支持)通过查询翻译。

相反,颠倒排序并使用相应的First 方法。

将其应用于您的案例意味着替换

.OrderBy(d => d.CreatedDate)

.OrderByDescending(d => d.CreatedDate)

.TakeLast(limit)

.Take(limit)

【讨论】:

    猜你喜欢
    • 2020-11-09
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2023-03-07
    • 1970-01-01
    • 2020-09-25
    相关资源
    最近更新 更多