C# 存储过程之后和事务内部更新实体
传入的类比C# 存储过程之后和事务内部更新实体,c#,entity-framework,transactions,C#,Entity Framework,Transactions,传入的类比 class Herd { public List<Animal> Animals { get; set; } } class Animal { //at least for today, animals have opinions public List<Opinion> Opinions { get; set; } } class Opinion { } 由于调用了一组存储过程,我只想将整个群体视为脏的,然后重新加载群体对象,但
class Herd
{
public List<Animal> Animals { get; set; }
}
class Animal
{
//at least for today, animals have opinions
public List<Opinion> Opinions { get; set; }
}
class Opinion { }
由于调用了一组存储过程,我只想将整个群体视为脏的,然后重新加载群体对象,但我找不到一种方法来实现这一点。我遗漏了什么?如果您跟踪此代码,您将看到在提交
trans
之前,默认的意见将不适用于新群体(我假设您使用的是默认的SQL Server隔离级别)。您可以通过使用嵌套事务来解决这个问题
//this will start a new transaction
using (var trans = new TransactionScope(TransactionScopeOption.RequiresNew))
{
try
{
_context.Herds.Add(herd);
_context.SaveChanges();
//this will use the "ambient" transaction but can commit separately
using (wrapperTransaction = new TransactionScope(TransactionScopeOption.Required))
{
Proc1Wrapper(herd);
Proc2Wrapper(herd);
Proc3Wrapper(herd);
InsertDefaultOpinionsProc(herd);
wrapperTransaction.Commit() //now your default opinions are inserted into the db
}
//this should return the herd now fully opinionated :)
herd = _context.Herds.First(o => o.HerdID == herd.ID);
AddOpinionsManually(herd);
_context.SaveChanges();
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
用
FavoritePlaces
或FavoriteFoods
来代替观点可能会更好,因为它们更明显地依赖于位置。哦,好的,谢谢!我将在项目再次处于可编译状态时测试它(不幸的是,可能需要24小时)。我还没有机会测试它。我有一个截止日期要赶,还有很多代码要写。我会尽快检查它,如果它有效,我会投票并接受。谢谢你。只是为了让你保持更新,我几乎完成了再次编译。不幸的是,它没有工作。它运行,但不加载意见。
//this will start a new transaction
using (var trans = new TransactionScope(TransactionScopeOption.RequiresNew))
{
try
{
_context.Herds.Add(herd);
_context.SaveChanges();
//this will use the "ambient" transaction but can commit separately
using (wrapperTransaction = new TransactionScope(TransactionScopeOption.Required))
{
Proc1Wrapper(herd);
Proc2Wrapper(herd);
Proc3Wrapper(herd);
InsertDefaultOpinionsProc(herd);
wrapperTransaction.Commit() //now your default opinions are inserted into the db
}
//this should return the herd now fully opinionated :)
herd = _context.Herds.First(o => o.HerdID == herd.ID);
AddOpinionsManually(herd);
_context.SaveChanges();
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}