Skip to content

Instantly share code, notes, and snippets.

@DmitrySikorsky
Created August 23, 2017 22:02
Show Gist options
  • Save DmitrySikorsky/45ab5c8efe0337983362d8070e9cb10c to your computer and use it in GitHub Desktop.
Save DmitrySikorsky/45ab5c8efe0337983362d8070e9cb10c to your computer and use it in GitHub Desktop.
public static int CountByRawSql(this DbContext dbContext, string sql, params KeyValuePair<string, object>[] parameters)
{
int result = -1;
SqlConnection connection = dbContext.Database.GetDbConnection() as SqlConnection;
try
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = sql;
foreach (KeyValuePair<string, object> parameter in parameters)
command.Parameters.AddWithValue(parameter.Key, parameter.Value);
using (DbDataReader dataReader = command.ExecuteReader())
if (dataReader.HasRows)
while (dataReader.Read())
result = dataReader.GetInt32(0);
}
}
// We should have better error handling here
catch (System.Exception e) { }
finally { connection.Close(); }
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment