我正在尝试将一系列数据库更新包装在事务范围内。我遇到了第一个数据库更新工作的问题,但第二个会失败。我认为这与我通过价值将 DbContext 传递给方法的报酬有关......本质上是在被调用的方法中创建它的副本(对吗?)。因此,我认为这导致了上下文没有保持完整的事务问题......这略高于我目前的理解水平并试图学习,但这是我目前的假设。
因此,我认为我需要通过引用将 DbContext 传递给被调用的方法,但随后会收到有关局部变量分配不正确的警告。
那么如何通过从 using 块中调用子方法来使用此封装并保持 DbContext 完整性?
这是我的包装方法:
// define our transaction scope
var scope = new TransactionScope(
// a new transaction will always be created
TransactionScopeOption.RequiresNew,
// we will allow volatile data to be read during transaction
new TransactionOptions()
{
IsolationLevel = IsolationLevel.ReadUncommitted
}
);
try
{
// use the scope we just defined
using (scope)
{
// create a new db context
var ctx = new InventoryMgmtContext();
using (ctx)
{
//Initial count of rows in Alloc Needs
System.Diagnostics.Debug.WriteLine("Begin Alloc Need Recs: " + ctx.AllocationNeeds.Count().ToString());
//De-Allocate inventory container dtls
var deAllocInvenResult = DeAllocInvenForNeed(ref ctx, intFacilityId, needSourceType, intNeedSourceId, intUserId);
//Delete Allocation Need and Allocated Ctnr records
var deleteAllocNeedResult = DeleteAllocRecords(
ref ctx,
intFacilityId,
needSourceType,
intNeedSourceId
);
//var repository = new Repository<AllocationNeed>(ctx);
}
// everything good; complete
scope.Complete();
}
这是进行更新的子方法之一:
//Delete Allocation Need and AllocatedContainers for alloc need id
private ActionConfirmation<int> DeleteAllocRecords(
ref InventoryMgmtContext ctx,
int intFacilityId,
AllocationNeed.NeedSourceTypeOptions needSourceType,
int intNeedSourceId
)
{
var repository = new Repository<AllocationNeed>(ctx);
//Delete Allocation Need and hence children in Allocated Containers
var srcType = needSourceType.ToString();
AllocationNeed allocNeed = repository.SearchFor(
x => x.FacilityId == intFacilityId
&& x.NeedSourceType == srcType
&& x.NeedSourceId == intNeedSourceId
).First();
//return repository.Delete(allocNeed, true);
ctx.Entry(allocNeed).State = System.Data.EntityState.Deleted;
ctx.SaveChanges();
//Deallocation was successful
return ActionConfirmation<int>.CreateSuccessConfirmation(
string.Format(
"Successfully deleted Need Id: {0} {1}",
needSourceType.ToString(),
intNeedSourceId
),
intNeedSourceId
);
}