TransactionScope功能 [英] TransactionScope functions
问题描述
在.net中处理事务。有关于通过子功能流动交易的问题。如果对象上下文在子方法中是常见的,是否需要使用从属事务?
Working on Transactions in .net. Had a question on flowing transactions through sub functions. Do I need to use dependent transactions if the object context is common across the sub - methods?
例如,在下面的代码中 - 我在我的类的构造函数中声明对象上下文(不知道这是否是最佳实践)
For example, in the following code - I declare the object context in the constructor of my class (not sure if this is best practice)
public class EmployeeRepository
{
private EmployeeContext ec;
public EmployeeRepository()
{
objectContext = new EmployeeContext();
}
public InitTransaction(EmployeeEntity emp1)
{
using (TransactionScope transaction = new TransactionScope())
{
try
{ ec.employees.AddObject(emp1);
SubFunction1();
ec.SaveChanges();
}
catch
{
//catch
}
}
//commit the transaction here
ec.AcceptAllChanges();
}
public SubFunction1()
{
//some processing
//using same object context
ec.someother.AddObject(someobject);
ec.SaveChanges();
}
}
我希望子功能成为交易的一部分还有吗
在这种情况下,即使我使用相同的对象上下文,我应该使用SubFunction1中的依赖事务吗?或者我应该使用(TransactionScope transaction = new TransactionScope())添加一个
I want the subfunctions to be a part of the transactions as well? In this case should I use a dependent transaction within SubFunction1 even though I am using the same object context? Or Should I add a
using (TransactionScope transaction = new TransactionScope());
指针正确方向将不胜感激。
within SubFunction1. Pointers in the right direction would be greatly appreciated.
推荐答案
事务范围可以嵌套(它们的工作方式类似于SQL @@ TRANCOUNT机制),因此您可以在理论上使用TransactionScopes在您的存储库中,例如保持父级:子表关系ACID,也可以在您的业务/服务层中(例如,跨多个实体分布式事务,跨多个数据库,甚至跨其他资源,如消息队列和交易文件系统。
Transaction Scopes can be nested (they work similar to the SQL @@TRANCOUNT mechanism), so you could in theory use TransactionScopes in your Repository, e.g. to keep parent : child table relationships ACID, but also in your Business / Service layers as well (e.g. to have a Distributed Transaction across multiple entities, possible across multiple Databases, and even across other resources such as Message Queues and Transactional file systems.
请注意,一个href =http://blogs.msdn.com/b/dbrowne/archive/2010/05/21/using-new-transactionscope-considered-harmful.aspx =nofollow noreferrer> TransactionScope的默认隔离级别是可序列化的 - 这可能导致锁定/死锁。
Note that the default isolation level of TransactionScope is Read Serializable - this can lead to locking / deadlocks.
这篇关于TransactionScope功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!