Created
August 23, 2017 22:02
-
-
Save DmitrySikorsky/45ab5c8efe0337983362d8070e9cb10c 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 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