c# - 在进行交易时无法找到实体
问题描述
我遇到了这个数据层方法的问题
public async Task<(bool HasFailed, IList<string> ErrorMessages)> ApproveBillCancelRequest(IEnumerable<string[]> billsToApprove,
string userId, string operationId)
{
var callerInfo = Shared.CommonAcross.Helper.GetCaller();
InfoScope($"{LayerName} -> {callerInfo.MethodName} -> Started", operationId, userId);
var errorMessages = new List<string>();
using (var context = new FocusConnection())
{
var transaction = context.Database.BeginTransaction();
try
{
foreach (var billToApprove in billsToApprove)
{
var targetBillNumber = billToApprove[0];
var targetPayModeId = int.Parse(billToApprove[1]);
var entityBill = context.BILL_INFO_CANCEL_REQUESTS
.SingleOrDefault(where =>
where.BILL_NUMBER == targetBillNumber &&
where.PAY_MODE_ID == targetPayModeId);
if (entityBill == null)
{
errorMessages.Add($"Bill #{billToApprove[0]}, payment #{billToApprove[1]} was not found for cancel approval");
continue;
}
entityBill.BILL_INFO.LAST_MODIFIED_BY = userId;
entityBill.BILL_INFO.STAMP_DATE = DateTime.Now;
entityBill.BILL_INFO.INPUT_STATUS = 0;
var cancelledBill = new BILL_INFO_CANCELED
{
BILL_NUMBER = entityBill.BILL_NUMBER,
PAY_MODE_ID = entityBill.PAY_MODE_ID,
CASHIER_ID = entityBill.CASHIER_ID,
CANCELED_DATE = entityBill.CANCEL_REQUEST_DATE,
CANCEL_REQUESTED_BY = entityBill.CANCEL_REQUESTED_BY,
CANCEL_APPROVED_BY = userId,
REMARKS = entityBill.CANCELATION_REASON
};
// Add cancelled bill
context.BILL_INFO_CANCELEDS.Add(cancelledBill);
// Remove cancellation request
context.BILL_INFO_CANCEL_REQUESTS.Remove(context.BILL_INFO_CANCEL_REQUESTS.Single(where =>
where.BILL_NUMBER == cancelledBill.BILL_NUMBER && where.PAY_MODE_ID == cancelledBill.PAY_MODE_ID));
await context.SaveChangesAsync();
}
transaction.Commit();
}
catch (Exception exp)
{
transaction?.Rollback();
ErrorScope($"{LayerName} -> {callerInfo.MethodName} -> Exception [{exp.Message}]", exp, operationId, userId);
errorMessages.Add($"{LayerName} -> {callerInfo.MethodName} -> Exception [{exp.Message}]");
return (true, errorMessages);
}
}
return (errorMessages.Any(), errorMessages);
}
问题是在 ForEach 循环中,第一条记录被正确检索和处理。但是剩余的记录永远找不到(entityBill == null
),但它们在数据库中。我相信这与正在运行的事务有关。
任何人都可以帮忙吗?
解决方案
这是一个很难破解的。事实证明,当 UI 层上的 String.Splitting() 时,有一个额外的空间被附加到数组列表中数组的第一个索引。所以我通过以下方式解决了这个问题:
var targetBillNumber = billToApprove[0].Trim();
var targetPayModeId = int.Parse(billToApprove[1].Trim());
推荐阅读
- python - 在 MongoDB 的嵌套条目中更改一个字段的 Pythonic 方法
- java - 类加载器是否可以获取已由不同类加载器加载的类?
- reactjs - redux状态对象内的数组排序后如何让React组件重新渲染
- excel - 一段时间后复制特定单元格
- devops - Azure DevOps Server 不会使用实时更新更新页面
- c# - 使用 .net sdk 在 couchbase 中进行子文档操作
- command-line-interface - OCI CLI 从对象存储中删除最旧的文件
- spring - 扩展ItemWriter Bean时如何在运行时使用@StepScope动态初始化ItemWriter Bean?
- c - 每次在 C 中打开时在下一行写入文本
- flutter - 未来的执行顺序