答案 0 :(得分:1)
最后,我决定重写批次,以便每个单独的项目都是独立保存的,所有这些都在一个大的交易中。换句话说,而不是:
var b = new Batch { ... };
while (addNewItems) {
...
var i = new BatchItem { ... };
b.BatchItems.Add(i);
}
b.Insert(); // that's a function in my library that calls SubmitChanges()
..你必须做这样的事情:
context.BeginTransaction(); // another one of my library functions
try {
var b = new Batch { ... };
b.Insert(); // save the batch record immediately
while (addNewItems) {
...
var i = new BatchItem { ... };
b.BatchItems.Add(i);
i.Insert(); // send the SQL on each iteration
}
context.CommitTransaction(); // and only commit the transaction when everything is done.
} catch {
context.RollbackTransaction();
throw;
}
你可以看到为什么第一个代码块更干净,使用更自然,很遗憾我被迫使用第二个结构......