Entity framework 在一次提交中保存来自不同类的多个对象

Entity framework 在一次提交中保存来自不同类的多个对象,entity-framework,repository-pattern,Entity Framework,Repository Pattern,我想知道保存多个对象的最佳方式是什么,如果第二个“obj.Insert()”抛出异常,所有更改都会回滚 我正在尝试这样的事情: Product product1 = new Product(); Product product2 = new Product(); Product product3 = new Product(); DbContext DB = new DB(); IProductInsert repository = new ProductInsert(DB); repos

我想知道保存多个对象的最佳方式是什么,如果第二个“obj.Insert()”抛出异常,所有更改都会回滚

我正在尝试这样的事情:

Product product1 = new Product();
Product product2 = new Product();
Product product3 = new Product();

DbContext DB = new DB();

IProductInsert repository = new ProductInsert(DB);

repository.Insert(product1);
repository.Insert(product2);
repository.Insert(product3);

DB.SaveChanges();
但在我看来,这是不对的


如何在我的存储库类中使用DB.SaveChanges()保存所有更改或回滚?

您应该能够使用事务作用域执行此操作:

using (var ts = new TransactionScope()) {
    repository.Insert(product1);
    repository.Insert(product2);
    repository.Insert(product3);
    DB.SaveChanges();
    ts.Complete();
}
如果此序列中出现任何失败,并且未到达调用
ts.Complete()
,则后台事务将回滚


有关跨多个db上下文工作的解决方案,请参阅。

您应该能够在事务范围内执行此操作:

using (var ts = new TransactionScope()) {
    repository.Insert(product1);
    repository.Insert(product2);
    repository.Insert(product3);
    DB.SaveChanges();
    ts.Complete();
}
如果此序列中出现任何失败,并且未到达调用
ts.Complete()
,则后台事务将回滚


有关跨多个db上下文工作的解决方案,请参阅。

niceee。。但是VS找不到System.Transaction。。为什么会这样?@murilokunze您需要将对
System.Transactions
的引用添加到项目的引用列表中(右键单击“引用”,选择“添加引用…”,打开“.NET”选项卡,然后从那里添加
System.Transactions
)。现在它可以工作了:。。但我还有一个疑问。。我应该在视图中使用transactionScope吗?@murilokunze否-设置事务作用域和执行数据库操作属于控制器代码,而不是视图代码。niceee。。但是VS找不到System.Transaction。。为什么会这样?@murilokunze您需要将对
System.Transactions
的引用添加到项目的引用列表中(右键单击“引用”,选择“添加引用…”,打开“.NET”选项卡,然后从那里添加
System.Transactions
)。现在它可以工作了:。。但我还有一个疑问。。我应该在视图中使用transactionScope吗?@murilokunze否-设置事务作用域和执行数据库操作属于控制器代码,而不是视图代码。