Last active
September 12, 2017 13:22
-
-
Save pietrom/640822acdcfa3902bdb5099f59d609b0 to your computer and use it in GitHub Desktop.
Utility methods for connection string handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Data; | |
| using System.Data.SqlClient; | |
| namespace Plastiline.Core.Utils.Sql { | |
| public static class ConnectionStringExtension { | |
| public static void Execute(this string connectionString, Action<IDbConnection> action) { | |
| using (IDbConnection conn = new SqlConnection(connectionString)) { | |
| conn.Open(); | |
| action(conn); | |
| } | |
| } | |
| public static void Execute(this string connectionString, Action<IDbConnection, IDbTransaction> action) { | |
| using (IDbConnection conn = new SqlConnection(connectionString)) { | |
| conn.Open(); | |
| using (IDbTransaction tx = conn.BeginTransaction()) { | |
| try { | |
| action(conn, tx); | |
| tx.Commit(); | |
| } catch (Exception) { | |
| tx.Rollback(); | |
| throw; | |
| } | |
| } | |
| } | |
| } | |
| public static T Execute<T>(this string connectionString, Func<IDbConnection, T> action) { | |
| using (IDbConnection conn = new SqlConnection(connectionString)) { | |
| conn.Open(); | |
| return action(conn); | |
| } | |
| } | |
| public static T Execute<T>(this string connectionString, Func<IDbConnection, IDbTransaction, T> action) { | |
| using (IDbConnection conn = new SqlConnection(connectionString)) { | |
| conn.Open(); | |
| using (IDbTransaction tx = conn.BeginTransaction()) { | |
| try { | |
| T result = action(conn, tx); | |
| tx.Commit(); | |
| return result; | |
| } catch (Exception) { | |
| tx.Rollback(); | |
| throw; | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment