TransactionScope functions

删除回忆录丶 提交于 2019-12-11 04:39:14

问题


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();
    }
}

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.


回答1:


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.

Note that the default isolation level of TransactionScope is Read Serializable - this can lead to locking / deadlocks.




回答2:


You can consider using Dependency Injection to pass around the same ObjectContext so you can avoid the TransactionScope.

Instead of creating Context inside the Repository inject it through constructor.

public class EmployeeRepository
{
    private EmployeeContext ec;        
    public EmployeeRepository(EmployeeContext objectContext)
    {
        ec = objectContext;            
    }       

}

Take a look at this answer



来源:https://stackoverflow.com/questions/7120738/transactionscope-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!