2

What is difference of these codes:

using (TransactionScope tran = new TransactionScope ())
{
     using (Entities ent = new Entities())
     {

and

using (Entities ent = new Entities())
{
    using (TransactionScope tran = new TransactionScope ())
    {

Does line order matter?

Thanks

2 Answers 2

1

In this case it wouldn't matter, since the Entities seems like Model / Data class, which cannot / needn't enlist into a transaction, so you can have any order, it would not create a difference. Now if the there's any issue in the Entities operation, Read / DML then transaction would also abort, assuming that operation takes place in the ambient transaction context, though class / object doing it like IDBConnection would anyway automatically enlisted into a transaction (provided not set to false), however even if Connection is created outside transaction context, then would not automatically enlist, needs explicit enlisting for Transaction Context

In Short

For your current code, it doesn't matter till the point you are dealing with an object that needs Transaction enlistment like IDBConnection. Out of two code snippets though my preference would be first one, where ambient transaction is all encompassing all the objects need to be enlist automatically does, we don't leave any object by chance.

Important Difference

What you though may want to be careful about whether you want to access Entities outside the Transaction Context, since that is not possible in the Option 1 but would not be an issue in the Option 2

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks But why did you say that my Model did not need enlist in to transaction? I want to use transaction with y entities
Model doesn't Enlist like Class Employee doesn't enlist but object like DBConnection or DBContext enlist, they are the one which work on the models and do transaction operations, this needs to be differentiated
1

Yes the order matters. Or rather we can't say it doesn't matter without looking at your code.

DbConnection instances will enist in an ambient transaction if one exists when they are Open()ed.

Your DbContext constructor might open the underlying DbConnection, in which case the two patterns differ.

The first one is the normal pattern, and you should stick to that.

Also if you are using SQL Server don't use the default constructor of TransactionScope. See Using new TransactionScope() Considered Harmful

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.