c# - ASP.NET Core Web API - 执行 'LastOrDefault' 操作的查询必须具有确定性排序顺序

标签 c# asp.net-core entity-framework-core

在使用 Entity Framework 的 ASP.NET Core-6 Web API 中,我有以下代码:

public async Task<Response<NotificationCredentialListDto>> CreateNotificationCredentialAsync(CreateNotificationCredentialDto requestDto)
{
    var userName = _currentUserService.UserName;
    var response = new Response<NotificationCredentialListDto>();
    using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
    {
        if (userName != null)
        {
            try
            {
                var notification = _mapper.Map<NotificationCredential>(requestDto);
                var existingNotification = _dbContext.NotificationCredentials.LastOrDefault(e => e.MerchantId == notification.MerchantId && e.IsModified == false);
                if (existingNotification != null)
                {
                    existingNotification.IsModified = true;
                    _unitOfWork.MerchantNotificationCredentials.Update(notification);
                    await _unitOfWork.Save();
                }
                requestDto.IsModified = false;
                notification.IsModified = requestDto.IsModified;
                notification.UserName = requestDto.UserName;
                requestDto.BasicAuth = encoded;
                notification.BasicAuth = requestDto.BasicAuth;
                notification.CreatedBy = _currentUserService.UserName;

                await _unitOfWork.MerchantNotificationCredentials.InsertAsync(notification);
                await _unitOfWork.Save();
                return response;
            }
            catch (Exception ex)
            {
                _logger.Error("An error occured: " + ex);
                transaction.Dispose();
                return response;
            }
        }
        _logger.Error("Registration failed");
        transaction.Dispose();
        response.StatusCode = (int)HttpStatusCode.BadRequest;
        response.Successful = false;
        response.Message = "Registration failed. Please try again";
        return response;
    }
}

我想要实现的是,如果记录存在,它应该将最后一条记录更新为:

IsModified = true

并插入一个新的。

但是我遇到了这个错误:

An error occured: System.InvalidOperationException: Queries performing 'LastOrDefault' operation must have a deterministic sort order. Rewrite the query to apply an 'OrderBy' operation on the sequence before calling 'LastOrDefault'.

如何解决这个问题?

谢谢

最佳答案

喜欢@Rafalon提到,在使用 LastOrDefault() 之前,您需要使用 OrderBy() 对集合进行排序。

var existingNotification = _dbContext.NotificationCredentials.OrderBy(e => e.CreatedAt).LastOrDefault(e => e.MerchantId == notification.MerchantId && e.IsModified == false);

但要小心,因为在调用 CreateNotificationCredentialAsync 之前可能已添加多条记录。也许您应该搜索 MerchantId = notification.MerchantIde.IsModified = false 的所有记录:

var existingNotifications = _dbContext.NotificationCredentials.Where(e => e.MerchantId == notification.MerchantId && e.IsModified == false).ToList();

并将 IsModified 属性更新为所有这些。

关于c# - ASP.NET Core Web API - 执行 'LastOrDefault' 操作的查询必须具有确定性排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73758003/

相关文章:

c# - 可疑类型转换解决方案中没有继承自两者的类型

.net - .net core 工具预览 2 是否有离线版本?

jquery - 如何单独影响每个元素的样式(悬停)

c# - Status Entities in .NET Core Entity Framework - 建议的实现

c# - 拦截并更改应用程序生成的 sql 查询

c# - Roslyn 分析器规则不会使构建失败

c# - 快速清除 NHibernate 数据库

C# 应用程序 - 读取 Google 通讯录

asp.net - 我如何告诉 IIS 使用我的 .NET 应用程序中的底层包罗万象的路由从 Web 根目录提供静态文件?

.net - 这是一种检查当前数据库上正在迁移的版本的方法