Created
March 3, 2016 18:03
-
-
Save crmckenzie/85836a103467c3507869 to your computer and use it in GitHub Desktop.
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
public int ExecuteSql(string sql, object parameters = null) | |
{ | |
int result; | |
using (var connection = ConnectToDb()) | |
using (var command = new SqlCommand(sql, connection)) | |
{ | |
Log.Info(sql); | |
if (parameters != null) | |
{ | |
var sqlParameters = ToSqlParameters(parameters); | |
command.Parameters.AddRange(sqlParameters.ToArray()); | |
} | |
connection.Open(); | |
result = command.ExecuteNonQuery(); | |
} | |
return result; | |
} | |
private IEnumerable<SqlParameter> ToSqlParameters(object parameters) | |
{ | |
var dictionary = ToDictionary(parameters); | |
foreach (var key in dictionary.Keys) | |
{ | |
var parameterName = string.Format("@{0}", key); | |
var parameterValue = dictionary[key]; | |
yield return new SqlParameter | |
{ | |
ParameterName = parameterName, | |
Value = parameterValue ?? System.DBNull.Value, | |
}; | |
} | |
} | |
private Dictionary<string, object> ToDictionary(object parameters) | |
{ | |
var properties = parameters | |
.GetType() | |
.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) | |
; | |
var query = from p in properties | |
let name = p.Name | |
let value = p.GetValue(parameters) | |
select new | |
{ | |
Key = name, | |
Value = value, | |
}; | |
var result = query.ToDictionary(row => row.Key, row => row.Value); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment