AdoNetPostgreSqlController.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Data.Common;
  6. using System.Web.Mvc;
  7. using Npgsql;
  8. using Benchmarks.Mono.AspNet.Models;
  9. namespace Benchmarks.Mono.AspNet.Controllers
  10. {
  11. public class AdoNetPostgreSqlController : Controller
  12. {
  13. private static string connectionString = ConfigurationManager.ConnectionStrings["PostgreSQL"].ConnectionString;
  14. public ActionResult Index(int? queries)
  15. {
  16. List<World> worlds = new List<World>(queries ?? 1);
  17. using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
  18. {
  19. connection.Open();
  20. using (NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM World WHERE id = @ID", connection))
  21. {
  22. Random random = new Random();
  23. for (int i = 0; i < worlds.Capacity; i++)
  24. {
  25. int randomID = random.Next(0, 10000) + 1;
  26. command.Parameters.Clear();
  27. command.Parameters.AddWithValue("@ID", randomID);
  28. using (DbDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow))
  29. {
  30. if (reader.Read())
  31. {
  32. World world = new World();
  33. world.id = reader.GetInt32(0);
  34. world.randomNumber = reader.GetInt32(1);
  35. worlds.Add(world);
  36. }
  37. }
  38. }
  39. }
  40. }
  41. return queries != null ? Json(worlds, JsonRequestBehavior.AllowGet)
  42. : Json(worlds[0], JsonRequestBehavior.AllowGet);
  43. }
  44. public ActionResult Fortunes()
  45. {
  46. List<Fortune> fortunes = new List<Fortune>();
  47. using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
  48. {
  49. connection.Open();
  50. using (NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM Fortune", connection))
  51. {
  52. using (DbDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
  53. {
  54. while (reader.Read())
  55. {
  56. Fortune fortune = new Fortune
  57. {
  58. ID = reader.GetInt32(0),
  59. Message = reader.GetString(1)
  60. };
  61. fortunes.Add(fortune);
  62. }
  63. }
  64. }
  65. }
  66. fortunes.Add(new Fortune { ID = 0, Message = "Additional fortune added at request time." });
  67. fortunes.Sort();
  68. return View(fortunes);
  69. }
  70. }
  71. }