This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Transactions in .net
I just wanted to know about Transaction in .net using c# language. I have gone through different articles on the net. However, I came to know about transaction theoretically but I wanted to know the exact use of it in real time. For example when exactly should I use transactions in real time. Let's suppose, I am writing code where I am doing some action on the click event of a link. Lets say, I am hitting the SQL connection to get some values. Should I use transaction there? If I am writing simple code, where I fetch values without using sql connection, should I use transactions there? What are the pros and cons of using Transactions. Getting theoritical knowledge is different, but I want to know the exact use of it. When to use when not to use. Can transactions be used in simple code? Any responses or links for even basic stuff about transactions are welcome.
I am hitting the SQL connection to get some values. Should I use
transaction there?
No, there are not need to use transactions, when you are not alter data in database.
What are the pros and cons of using Transactions.
As you said, you have learned various articles, So may be you have figure out the reason of using the transactions. Look all of these in concern of database.
The advantages of three-tier applications in creating scalable and robust applications are made feasible by transaction processing systems. The ability to distribute the components that make up applications amongst separate servers without explicitly having to develop for that architecture is another advantage of transaction server processing. Transaction processing systems also ensure that transactions are atomic, consistent, isolated, and durable. This alleviates the developer from having to support these characteristics explicitly.
Why Do We Need Transaction Processing?
The Advantages Of Transaction Processing
Can transactions be used in simple code?
Yes, you can simply write code in C# using ADO.Net. (e.g. SQLTransaction class)
e.g.
SqlConnection db = new SqlConnection("connstringhere");
SqlTransaction transaction;
db.Open();
transaction = db.BeginTransaction();
try
{
new SqlCommand("INSERT INTO TransactionDemo " +
"(Text) VALUES ('Row1');", db, transaction)
.ExecuteNonQuery();
new SqlCommand("INSERT INTO TransactionDemo " +
"(Text) VALUES ('Row2');", db, transaction)
.ExecuteNonQuery();
new SqlCommand("INSERT INTO CrashMeNow VALUES " +
"('Die', 'Die', 'Die');", db, transaction)
.ExecuteNonQuery();
transaction.Commit();
Reference:
Performing a Transaction Using ADO.NET
.NET 2.0 transaction model
Refer this article:
http://www.codeproject.com/Articles/10223/Using-Transactions-in-ADO-NET
This will answer you questions about Transactions.
The essence of transaction is to make sure that one or more changes that represent a single process get to database once and if one of them fail, the others should be reversed. If you are transferring money from one bank account to another, the deduction from one account and the depositing to the other account must be successful altogether. Otherwise, money would be lost in transit
using(SqlConnection conn = new SqlConnection())
{
try
{
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
//command to remove from account A
//command to deposit into account B
tran.Commit(); //both are successful
}
catch(Exception ex)
{
//if error occurred, reverse all actions. By this, your data consistent and correct
tran.Rollback();
}
}
Another alternative is TransactionScope, System.Transactions
If you are serious about using Transactions you can also read some Articles about the TransactionScope class in .NET . It's very simple to implement Transactions this way.
http://simpleverse.wordpress.com/2008/08/05/using-transactionscope-for-handling-transactions/
Example:
using ( var transaction = new TransactionScope() )
{
// My Database Operations. It doesn't matter what database Type
transaction.Complete();
}
generally you as most have suggested should probably be using TransactionScope, although this does come with some bits to be aware of.
using(TransactionScope ts = TransactionUtils.CreateTransactionScope()){
using(SqlConnection conn = new SqlConnection(connString)){
conn.Open();
using(SqlCommand cmd = new SqlCommand("DELETE FROM tableName WHERE somethingorother", conn)){
cmd....
}
using(SqlCommand cmd ....) ...
thingy.Save();//uses another command/connection possibly
}
//all above Sql Calls will be done at this point. all or nothing
ts.Complete();
}
depending on how it is used (and what DB/version you are using), TransactionScope may escalate the transaction to MSDTC, which would need setting up on the machine running the app (dcomcnfg from the run prompt). ( TransactionScope automatically escalating to MSDTC on some machines? )
also worth having a read of this
http://blogs.msdn.com/b/dbrowne/archive/2010/06/03/using-new-transactionscope-considered-harmful.aspx
rather than blankly using a new TransactionScope() - that article suggests making a static method to generate one with some more helpful defaults.
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);
}
}
hth
I can tell you that using transactions depends on the business rules.
Technically, you may use transactions only if you are modifying data (Update, Delete, Insert) on the systems. When you are just getting values from a source and you are 100% sure that no data gets modified/produced, then don't include this step as part of your transaction.
To keep it simple, use transactions if you answer yes to any of these scenarios:
a) Affect more than one table in your click.
b) Affect more than one system in your click. This includes databases located in different servers, even if you have two different instances in the same server it counts as a different system. Web service calls count as another system as well.
c) Have an scenario like: "perform step a, perform step b, if everything OK then return OK else revert step b, revert step a then return error".
Now how to use transactions in real world. Well, if you are using only one database in your model then use the ADO.NET transaction model.
http://adotutorial.blogspot.de/2008/11/transaction-management-in-adonet.html
If you however, are calling different instances of databases in the same server, or if you you are mixing different technologies (SQL, Oracle, Web Services), transaction management will be 1000 times more painful. Then you need to use transaction scope make it a little bit simpler. In C# in .NET 2.0 you have TransactionScope. This is the way that you can tell the run-time to help us manage transactions.
Check this tutorial, it may help.
http://codingcramp.blogspot.de/2009/06/how-to-setup-and-use-transactionscope.html
If you are using microsoft technologies and if you are working on the same computer, then your code wil run fine. However, if you are running in a networked environment, or if you are mixing different vendors, then another key component enter in the play it is called a "Transaction Monitor". If that is your case then you may need to check if Microsoft DTC is enabled in your environment as it will be the default choice used for coordinating your transactions.
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
I am making a winform application in c#. I need to update/insert or delete two different tables in two different databases on two different servers and I want to do it with transaction (If update in one database fails, the other will be rolled back.)
How can I do it, please give some code in c# and also state whether it is good to do mysql transaction over two different servers (I mean, is there any chances that database will get corrupted by poor implementation of distributed transaction as I read this in some forum).
I searched over internet but I could not find c# code.
Thank you
I suggest you try using the TransactionScope class.
Simply wrap your two sql statements in a transaction scope and they should both commit or rollback together.
using(var transaction = new System.Transactions.TransactionScope())
{
... Add your transactional code here ...
transaction.Complete();
}
I'm not sure this will work but it will give you a place to start and should be simple to test.
I've been reading a document from Microsoft's patterns & practices group (Data Access for Highly-Scalable Solutions: Using SQL, NoSQL, and Polyglot Persistence).
In Chapter 3, in the section "Retrieving Data from the SQL Server Database", the authors discuss using Entity Framework to load entities from a database. Here's a bit of their sample code:
using (var context = new PersonContext())
{
Person person = null;
using (var transactionScope = this.GetTransactionScope())
{
person = context.Persons
.Include(p => p.Addresses)
.Include(p => p.CreditCards)
.Include(p => p.EmailAddresses)
.Include(p => p.Password)
.SingleOrDefault(p => p.BusinessEntityId == personId);
transactionScope.Complete();
}
// etc...
}
Note the use of a custom transaction scope via the GetTransactionScope method, implemented in their base context class like so:
public abstract class BaseRepository
{
private static TransactionOptions transactionOptions = new TransactionOptions()
{
IsolationLevel = IsolationLevel.ReadCommitted
};
protected virtual TransactionScope GetTransactionScope()
{
return new TransactionScope(TransactionScopeOption.Required, transactionOptions);
}
}
Working with Transactions (EF6 Onwards) on MSDN states:
In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete on the database the framework will wrap that operation in a transaction [...] the isolation level of the transaction is whatever isolation level the database provider considers its default setting. By default, for instance, on SQL Server this is READ COMMITTED. Entity Framework does not wrap queries in a transaction. This default functionality is suitable for a lot of users
The bold emphasis is mine.
My question: is the use of a TransactionScope as shown above overkill, particularly for data reads, when using Entity Framework?
(I realised after posting that the answer to this question might be somewhat opinion-based, sorry about that.)
The question is a little open ended. But may prove useful for people learning about dirty reads. Isolation and EF.
And you have read EF Transaction Scope ef6 and we have a clear question.
Generally i would say let EF manage the scope.
Beginners dont consider uncommitted reads and it is a good default for EF.
You may have a valid reason to want to control scope.
Or need to use an existing transaction. But remains for specialist use.
So now the real question.
Is it good practice to include such defensive programming around isolation.
My view:
Only if it doesnt make the code harder to maintain, and harder to reuse.
Oracle and SQL server have default Read Committed. I would expect so on other DBs.I would therefore conclude, most likely unecessary protection that adds complexity.
I wouldnt add it to my code.
It depends.
If you want dirty reads, serializable reads,etc anything other than default isolation level, then you need to wrap you queries inside a transaction scope.
To maintain data integrity, it is sometimes useful to use an explicitly defined multi-statement transaction so that if any part of the transaction fails, it all gets rolled back. The decision on whether or not to use a transaction should not be entered into lightly. Explicit transactions, especially distributed ones, come at a major cost to performance and open the system up to deadlocks and to the possibility that a transaction could be left open, locking the affected table and blocking all other transactions. In addition, the code is far more difficult to develop and maintain.
In my experience, I have found that using a transaction scope in C# code is more complicated than using an explicit transaction in SQL. So for operations that would benefit from a transaction, and really any sufficiently complicated query, I would recommend creating a stored procedure to be called from the ORM.
Have you read the following link ?
https://msdn.microsoft.com/en-us/library/vstudio/bb738523%28v=vs.100%29.aspx
If you were to use the normal behavior of saveChanges without it begin part of a transactionscope you would not be able to extend the transaction beyond the boundaries of the database. Using the transaction scope like in the reference above makes the message queue part of the transaction. So if for some reason the sending of the message fails, the transaction fails too.
Of course you might consider this a more complex scenario. In simple applications that don't require such complex logic, you are probably safer to use the plain saveChanges api.
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.
What is best practice for C# Window Forms and SQL connection instance. I need the same SQL connection in all window forms. What is best implementation practice for this? Where do I put the SQL connection?
I am using Compact framework 3.5.
Personally I prefer to leave connection management to the ADO.NET connection pool and everytime I want to query:
using (var conn = new SqlConnection("connection string"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id FROM foo;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// ...
}
}
}
When you call conn.Open() a physical connection is not opened, it is drawn from the connection pool, and when the using block end and invokes .Dispose the connection is not closed but returned to the connection pool in order to be reused. This improves performance and relieves me from worrying about where to put or store those SqlConnection instances in applications.
You say you need the same connection in all your forms, but I don't think you should consider that to be axiomatic. You may well need to connect to the same database in all forms, but that's not the same thing - any more than you would need to use the same connection to make multiple requests to a web service.
I would strongly suggest three things:
Use dependency injection to allow a single object to be provided to multiple classes/objects which all need it
Don't inject the actual connection: inject something which can provide a connection, or perhaps just something which can execute a query for you.
Take code which accesses the database out of the user-interface code so you can test each independently of the other.
Generally speaking, database access should be (from the caller's point of view): "open connection, do work, close connection whatever happened" (as per Darin's answer). Let .NET's connection pooling take care of the physical connection to the database. How you structure your code around that will depend on your requirements, and the extent to which they vary between forms. In many cases you may be able to get away with just asking your database access class to execute a query for you with a certain set of parameters and return the results - in other cases you may need more fine-grained control.
As Dimitrov suggested a good approach is to open and close connections only when needed and keep it open the shortest possible time. .NET Connection pool will handle this for you so connections will be reused in a transparent way for you.
In general a good approach is to have another class library to serve as Data Access Layer which wraps the calls to database and does not expose any connection or command usage to the UI, so in the future you would be able to move to another database engine, if needed, changing only the DAL.
Communication from DAL and UI should consist only in objects (entities) or for simple projects DataTables and DataSets. In most of the cases a third project (class library) is in the between and it's called Business Logic, such level manipulates the data from DAL and applies your application specific business logic returning cleaner or elaborated results to the UI.
I have used this approach in many projects already, since about 11 years.
You should make a class with the connection logic in.