在使用 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.MerchantId
和 e.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/