Yes, you can create a global SqlConnection instance. In my case I use the SqlConnection as member of my DataContext that I access via Singleton.
public class DatabaseDataContext : DataContext
{
private static DatabaseDataContext instance;
private SqlConnection sqlConnection;
private SqlTransaction sqlTransaction;
//...
public static DatabaseDataContext Instance
{
get
{
return instance ?? (instance = new DatabaseDataContext(connectionString));
}
set
{
instance = value;
}
}
}
You can encapsulate your transactions by closing and opening this connection, i.e.:
DatabaseDataContext.Instance.sqlConnection.Open();
// your transactions...
sqlConnection.Close();
Or you might leave the connection open, but instead specifically begin and end transactions:
DatabaseDataContext.Instance.sqlConnection.Open();
sqlTransaction = sqlConnection.BeginTransaction("Example Insert users");
try{
// ...your first transaction
sqlTransaction.Commit();
}
catch{sqlTransaction.Rollback();}
sqlTransaction = sqlConnection.BeginTransaction("Update baked breads");
try{
// ...your second transaction
sqlTransaction.Commit();
}
catch{sqlTransaction.Rollback();}
// Close the connection at some point
sqlConnection.Close();
using
block) – Designed