I am using WF, and need to support transactions and persistence.
I would like not to use the TransactionScopeActvity , but use my own transaction scope object, and still have a persistence point at the end which will be part of the transaction in the activity itself (similar to how the TransactionScopeActvity works on this aspect). I can achieve a persistence point at the end of the transaction by using the "PersistOnClose" attribute, but to what transaction will the persistence call belong to? will it open a new transaction, or look for the ambient transaction? How can I assure that an ambient transaction exists when the persistence point is activated?
Version 3 and 3.5 does not support ambient transaction I faced a lot of Issues designing around this In the new version of workflow i.e. 4.0 (which is complete rewrite from ground up ) supports Ambient Transaction
Related
I just want to know if I want to rollback all changes in database if transaction not complete, is there any difference between
using (TransactionScope transaction = new TransactionScope())
and
using (var dbContextTransaction = context.Database.BeginTransaction())
I am confused when read these two:
Connection.BeginTransaction and Entity Framework 4?
and
https://learn.microsoft.com/en-us/ef/ef6/saving/transactions
**note that I use entity framework 4 in my project if its necessary
From Programming Microsoft SQL Server 2012:
There are a number of pain points with explicit transactions. The first difficulty lies in the requirement that every SqlCommand object used to perform updates inside the transaction must have its Transaction property set to the SqlTransaction object returned by BeginTransaction. This means that you must take care to pass along the SqlTransaction object to any place in your code that performs an update, because failing to assign it to the Transaction property of every SqlCommand object in the transaction results in a runtime exception. The issue is compounded when you need to track the SqlTransaction object across multiple method calls that perform updates. It becomes even harder to manage things when these methods need to be flexible enough to work whether or not a transaction is involved or required.
The problem is worse when working with any of the other technologies we'll be covering later that provide abstraction layers over the raw objects. For example, because a SqlDataAdapter actually wraps three distinct SqlCommand objects (for insert, update, and delete), you must dig beneath the data adapter and hook into its three underlying command objects so that you can set their Transaction properties. (We don't generally recommend that you mix and match different data access APIs within your application, but if you must transactionalize updates across a combination of technologies, implicit transactions make it easy.)
The TransactionScope object, introduced as part of a dedicated transaction management API with .NET 2.0 in 2005, lets you code transactions implicitly. This is a superior approach that relieves you from all of the aforementioned burdens associated with explicit transactions. So the guidance here is to always work with implicit transactions whenever possible. You will write less code that is more flexible when you allow the framework to handle transaction management for you. However, it is still also important to understand explicit transactions with the SqlTransaction object, as you might need to integrate with and extend existing code that already uses explicit transactions. Therefore, we will cover both transaction management styles to prepare you for all situations.
The transaction management API offers many more benefits besides implicit transactions. For example, TransactionScope is capable of promoting a lightweight transaction (one associated with a single database) to a distributed transaction automatically, if and when your updates involve changes across multiple databases.
There are two pitfalls with TransactionScope you should be aware of.
First is that it will, by default, create a transaction with SERIALIZABLE isolation level, which, for SQL Server, is a poor choice. So you should always create your TransactionScope like this:
public class TransactionUtils
{
public static TransactionScope CreateTransactionScope()
{
var transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted;
transactionOptions.Timeout = TransactionManager.MaximumTimeout;
return new TransactionScope(TransactionScopeOption.Required, transactionOptions);
}
}
See rant here: using new TransactionScope() Considered Harmful
The second is that TransactionScope supports Distributed Transactions. So it will enable you to enlist different connections and even different resource providers in a single transaction. While this is occasionally useful, it's more often a pitfall. If you accidently end up with a distributed transaction you can accidently take a dependency on having a distributed transaction coordinator in your environment. So you should take steps to avoid having a distributed transaction, like shutting down Microsoft Distributed Transaction Coordinator (MSDTC) in your development environment. And ensure that any time you have multiple methods enlisted in a transaction, they don't both have a SqlConnection open at the same time.
While Database. BeginTransaction() is used only for database related operations transaction, System. Transactions. ... TransactionScope for mixing db operations and C# code together in a transaction.
please see Below Links.Hope they help you:
TransactionScope vs Transaction in LINQ to SQL
Database.BeginTransaction vs Transactions.TransactionScope
This question already has an answer here:
C# System.Transactions Vs TransactionScope
(1 answer)
Closed 2 years ago.
What is the difference between System.Transactions.TransactionScope and EF6's Database.BeginTransaction?
Could someone give a small example or just explain which one to use when with a clear difference?
P.S: In my project, I'm using EF6. I've already read the documentation but it didn't help much. Also looked up the examples but they are rather using SqlConnection.BeginTransaction and now MS has introduced this new Database.BeginTransaction in EF6.
I found out the answer in Entity Framework 6's documentation:
With the introduction of EF6, Microsoft recommends to use new API methods: Database.BeginTransaction() and Database.UseTransaction(). Although System.Transactions.TransactionScope is still very well supported, it is no longer necessary for most users of EF6.
While Database.BeginTransaction() is used only for database related operations transaction, System.Transactions.TransactionScope, in addition to that, makes it possible for 'plain C# code' to also be transactional.
Hence, use Database.BeginTransaction() where ever doing only db related operations in a transaction in EF6 otherwise use System.Transactions.TransactionScope for mixing db operations and C# code together in a transaction.
For those who still prefer the TransactionScope approach, it is recommended they checkout its limitations, especially in cloud scenarios (cloud scenarios do not support distributed transactions).
Further information can be found here
The accepted and popular answer is misleading.
Both Database.BeginTransaction() and System.Transactions.TransactionScope are for DB operations.
The main differences between Database.BeginTransaction() and System.Transactions.TransactionScope:
Style
With TransactionScope you set the transactions implicitly in the background (by wrapping all transactional actions with a starting using scope = new TransactionScope and an ending scope.Complete(); to commit.
With Database.BeginTransaction the transaction is set explicitly by writing sqlCommand.Transaction = sqlTxn; and context.Database.UseTransaction(sqlTxn);
Distributed Transactions
TransactionScope supports both distributed transactions (where multiple DB involved in a single transaction) and non-distributed transactions.
Database.BeginTransaction only supports non-distributed transactions (a local transaction where all actions are done within a single DB).
MSDN do state that with the new Database.BeginTransaction() and Database.UseTransaction() APIs, the TransactionScope approach is no longer necessary for most users.
Async Support
For async support the TransactionScope should be passed the AsyncFlow enabled flag - TransactionScope(TransactionScopeAsyncFlowOption.Enabled); in case await is used after opening the transaction (e.g. await _myReop.SaveItemAsync(item);).
Advantages and disadvantages of TransactionScope:
Disadvantages of TransactionScope:
Requires .NET 4.5.1 or greater to work with asynchronous methods.
It cannot be used in cloud scenarios unless you are sure you have one and only one connection (cloud scenarios do not support distributed transactions).
It cannot be combined with the Database.UseTransaction() approach of the previous sections.
It will throw exceptions if you issue any DDL and have not enabled distributed transactions through the MSDTC Service.
Advantages of TransactionScope:
It will automatically upgrade a local transaction to a distributed transaction if you make more than one connection to a given database or combine a connection to one database with a connection to a different database within the same transaction (note: you must have the MSDTC service configured to allow distributed transactions for this to work).
Ease of coding. If you prefer the transaction to be ambient and dealt with implicitly in the background rather than explicitly under you control then the TransactionScope approach may suit you better.
Based on this MSDN article.
I want to find a way to control EF's underlying db connection & transaction to make sure my application is using only one connection at a time during one transaction (I will need to support both Oracle and SQL Server).
I found this good article which comes with a lot of recommendations, but brings up (like all the other articles I have read) the TransactionScope. Well, I would like to stay away of TransactionScope, if possible...
Could I have a solution for this playing with only pure DbConnection & DbTransaction or this is simply impossible or wrong?
Even more, I found this article here, stating at section :
"Specifying Your Own Transaction"
Just as you can override the default behavior with connections, you
can also control transaction functionality. If you explicitly create
your own transaction, SaveChanges will not create a DbTransaction. You
won't create a System.Common.DbTransaction, though. Instead, when
creating your own transactions, you need to use a
System.Transaction.TransactionScope object.
But there is no explaination...
I am using Entity Framework 5.0. Could you please help me understand in order to choose correct for my application? It would be ideal to show me some good patterns of usage.
Thanks in advance!
Note: I am planning this because of the transactions escalating to DTC for Oracle Data Provider.
Entity Framework 6 has two features which may help with this:
Explicit Transaction Support
Ability to create a DbContext from a DbConnection.
If you did want to use EF5, you'd need to use a TransactionScope:
var context = new MyContext();
using (var transaction = new TransactionScope())
{
MyItem item = new MyItem();
context.Items.Add(item);
context.SaveChanges();
item.Name = "Edited name";
context.SaveChanges();
transaction.Complete();
}
As mentioned in the linked article, you will need to reference System.Transactions to get TransactionScope.
Entity Framework maintains its own transaction which is sufficient. However it gives you flexibility of committing or discarding the changes in transaction. If you do not call SaveChanges() method then it will discard the transaction. Also if you are using the same DbContext for many transactions, then it would be using same connection. If you use two or more DbContext at the same time, then it will use separate connections which is ideal situation. Here is a very important point I would like to make is that it would be a waste of Entity Framework technology to implement own transaction. If you want to do so, then I would suggest to use your own DB implementation in traditional way.
I'm looking for a reference implementation of the "Unit of work" and "repository" pattern for MS SQL Server or Plain old ADO.NET. But all samples are build aroud an existing context like Linq2SQL or EF. According to my understanding, these technologies are themselves almost implementing these pattern.
But how do I deal with a "plain" SQL Repository without any context and SaveChanges() methods? Is the right way to use TransactionScope? For example collect all SQL Operations in a List of commands and then simple execute them one after each other within a Tx Scope... or is this too simple?
Why am I looking for this? I have the task of building a data layer that can both deal with an ancient Sybase database as well as SQL Server (maybe additional in conjunction with a POCO based EF4 Component)
For this my Idea is to create an abstraction layer with a Repository and Unit of Work Pattern and create different implementations for each Technology.
Update:
I was on vacation the last week. Sorry for the delay. Today I built up an basic picture of my architecture for this. [link] (s7.directupload.net/file/d/2570/whb7ulbs_jpg.htm). My idea is to create a simple ObjectContext like the EF ObjectContext that exists parallel to the EF Context and is used by my repository. This context collects ATOM Sql Transactions in a kind of Stack and executes them within the Transaction within the Unit of Work part. Good idea? Bad Idea? Hard to do? I'm looking forward to your views on this.
I don't envy your task; supporting multiple backend databases in your application is going to be tricky.
Here's an example of a Unit Of Work pattern using ASP.NET MVC and LightSpeed: link
Personally, I would use EF or NHibernate (prefer EF); SQL Anywhere supports ADO.NET and Entity Framework, so (ideally) you wouldn't need to do anything special to support that database.
Good luck!
If you are just worried about transaction scope, let me point you towards the System.Transactions library, and its TransactionScope object. Great class. any sql or other transaction managed system that is manipulated within the same thread that instantiated the transaction scope will be automatically added to the transaction. that way, if any part of the code fails, and throws an exception, you can just not call the scope.Complete() method and all the operations within the transaction scope are rolled back. very nice class.
I am developing an application which communicates with an SQL Server 2005 database to execute some stored procedures. My client demands that all transactions be managed on the C# side and not by SQL Server, and so I am using System.Transactions.TransactionScope when accessing the database. However, I have just seen the System.Transactions.Transaction datatype, and I am confused... What are the main pros/cons of each type? Which one should I use?
Please note that I must also use Enterprise Library's Data Access Application Block.
From msdn :
The TransactionScope class provides a
simple way to mark a block of code as
participating in a transaction,
without requiring you to interact with the transaction itself. A
transaction scope can select and
manage the ambient transaction
automatically. Due to its ease of use
and efficiency, it is recommended that
you use the TransactionScope class
when developing a transaction
application. When you instantiate
TransactionScope, the transaction
manager determines which transaction
to participate in. Once determined,
the scope always participates in that
transaction. The decision is based on
two factors: whether an ambient
transaction is present and the value
of the TransactionScopeOption
parameter in the constructor. The
ambient transaction is the transaction
within which your code executes. You
can obtain a reference to the ambient
transaction by calling the static
Current property of the Transaction
class.
You can read more about that here :
http://msdn.microsoft.com/en-us/library/ms172152(v=vs.90).aspx
http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope(v=vs.90).aspx
Great (a bit old) article about transaction in .NET 2.0
http://msdn.microsoft.com/en-us/library/ms973865.aspx