DbModule.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. namespace NancyModules
  2. {
  3. using System;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Linq;
  7. using Dapper;
  8. using MySql.Data.MySqlClient;
  9. using Nancy;
  10. public class DbModule : NancyModule
  11. {
  12. public static string MYSQL_CONNECTION_STRING;
  13. static DbModule()
  14. {
  15. MYSQL_CONNECTION_STRING = ConfigurationManager.AppSettings["ConnectionString.MySQL"];
  16. }
  17. /**
  18. * NOTE:
  19. * Return a single World objects as JSON, selected randomly from the World
  20. * table. Assume the table has 10,000 rows.
  21. */
  22. public DbModule() : base("/db")
  23. {
  24. Get["/{queries?1}"] = paramz =>
  25. {
  26. var random = new Random();
  27. using (var db = new MySqlConnection(MYSQL_CONNECTION_STRING))
  28. {
  29. db.Open();
  30. return Response.AsJson(GetRandomWorld(db, random));
  31. }
  32. };
  33. }
  34. private World GetRandomWorld(IDbConnection db, Random random)
  35. {
  36. var id = random.Next(1, 10001);
  37. return db.Query<World>("SELECT id, randomNumber FROM world WHERE id = @id", new { id = id }).Single();
  38. }
  39. }
  40. public class World
  41. {
  42. public int id { get; set; }
  43. public int randomNumber { get; set; }
  44. }
  45. }