UnitOfWork 不会根据条件更新所有项目
本文关键字:更新 项目 条件 UnitOfWork | 更新日期: 2023-09-27 18:30:48
我有这个方法:
public bool UpdateOfficeApprovers(IList<int> invoiceLinesToUpdate, int userId)
{
foreach (var invoiceLineId in invoiceLinesToUpdate)
{
var invoiceLine = _unitOfWork.InvoiceLineRepository.Get(invoiceLineId);
invoiceLine.OfficeUserId = userId;
if (!invoiceLine.HasTwoUniqueApprovers)
{
// do something here to avoid this line being updated
}
}
_unitOfWork.Save();
return hasUniqueApprovers;
}
我在这里要做的是遍历所有发票行并更新它们的OfficeUserId。但是,HasTwoUniqueApprovers
条件,如果这是false
,我不想更新此发票行,而只是保留它。
好的,所以行:
invoiceLine.OfficeUserId = userId;
将实体状态更新为EntityState.Modified
正确吗?
所以当:
_unitOfWork.Save();
这将保存所有发票,因为它保存了所有内容:
EntityState.Modified
所以我想知道的是如何阻止某些发票被更新。
那么,当发票行满足条件时,我该如何设置它,使其不会被更新?
检查的因斯特德!有两个唯一批准者;只需检查实体是否有两个唯一批准者然后更新此实体。其他具有"HasTwoUniqueApprovers"假的实体将处于不变状态,并且不会在对象上下文中进行处理。
public bool UpdateOfficeApprovers(IList<int> invoiceLinesToUpdate, int userId)
{
foreach (var invoiceLineId in invoiceLinesToUpdate)
{
var invoiceLine = _unitOfWork.InvoiceLineRepository.Get(invoiceLineId);
if (invoiceLine.HasTwoUniqueApprovers)
{
invoiceLine.OfficeUserId = userId;
}
}
_unitOfWork.Save();
return hasUniqueApprovers;
}
不为不想
保存的行设置OfficeUserId
,或者将其状态设置回"未更改"。
objectContext.ObjectStateManager.ChangeObjectState(invoiceLine, EntityState.Unchanged);
或在 DbContext API 中:
dbContext.Entry(invoiceLine).State = EntityState.Unchanged;