Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. public static int CountByRawSql(this DbContext dbContext, string sql, params KeyValuePair<string, object>[] parameters)
  2. {
  3. int result = -1;
  4. SqlConnection connection = dbContext.Database.GetDbConnection() as SqlConnection;
  5.  
  6. try
  7. {
  8. connection.Open();
  9.  
  10. using (SqlCommand command = connection.CreateCommand())
  11. {
  12. command.CommandText = sql;
  13.  
  14. foreach (KeyValuePair<string, object> parameter in parameters)
  15. command.Parameters.AddWithValue(parameter.Key, parameter.Value);
  16.  
  17. using (DbDataReader dataReader = command.ExecuteReader())
  18. if (dataReader.HasRows)
  19. while (dataReader.Read())
  20. result = dataReader.GetInt32(0);
  21. }
  22. }
  23.  
  24. // We should have better error handling here
  25. catch (System.Exception e) { }
  26.  
  27. finally { connection.Close(); }
  28.  
  29. return result;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement