DBDataProvider.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using sql_pagining.models;
  7. using Dapper;
  8. using MySqlConnector;
  9. namespace sql_pagining.models
  10. {
  11. internal class DBDataProvider : IDataProvider
  12. {
  13. private string searchFilter = "";
  14. private Dictionary<string, object> filters = new Dictionary<string, object>();
  15. private string orderCondition = "";
  16. static string connectionString = "Server=kolei.ru; User ID=sbahtina; Password=010906; Database=sbahtina";
  17. public IEnumerable<Product> getProduct(int pageNum)
  18. {
  19. using (MySqlConnection db = new MySqlConnection(connectionString))
  20. {
  21. var builder = new SqlBuilder();
  22. if (orderCondition.Length > 0)
  23. builder.OrderBy(orderCondition);
  24. if (filters.Count > 0)
  25. {
  26. foreach (var item in filters)
  27. builder.Where(item.Key, item.Value);
  28. }
  29. var template = builder.AddTemplate(
  30. "SELECT * FROM ProductView /**where**/ /**orderby**/ LIMIT @pageLen OFFSET @offset",
  31. new { pageLen = Globals.PAGE_LEN, offset = (pageNum - 1) * Globals.PAGE_LEN }
  32. );
  33. return db.Query<Product>(
  34. template.RawSql,
  35. template.Parameters).ToList();
  36. }
  37. }
  38. public int getProductCount()
  39. {
  40. using (MySqlConnection db = new MySqlConnection(connectionString))
  41. {
  42. var builder = new SqlBuilder();
  43. if (filters.Count > 0)
  44. {
  45. foreach (var item in filters)
  46. {
  47. builder.Where(item.Key, item.Value);
  48. }
  49. }
  50. var template = builder.AddTemplate(
  51. "SELECT count(*) FROM ProductView /**where**/");
  52. return db.QuerySingle<int>(
  53. template.RawSql,
  54. template.Parameters);
  55. }
  56. }
  57. public void setOrder(string condition)
  58. {
  59. orderCondition = condition;
  60. }
  61. public void addFilter(string name, object value)
  62. {
  63. filters.Add(name, value);
  64. }
  65. public void clearFilter()
  66. {
  67. filters.Clear();
  68. }
  69. public IEnumerable<ProductType> getProductTypes()
  70. {
  71. using (MySqlConnection db = new MySqlConnection(connectionString))
  72. {
  73. return db.Query<ProductType>("SELECT * FROM ProductType");
  74. }
  75. }
  76. public void setMinCostForAgent(decimal minCostForAgent, int[] ids)
  77. {
  78. using (MySqlConnection db = new MySqlConnection(connectionString))
  79. {
  80. db.Execute("UPDATE Product SET MinCostForAgent=@newCost WHERE ID in @idList",
  81. new
  82. {
  83. newCost = minCostForAgent,
  84. idList = ids
  85. });
  86. }
  87. }
  88. }
  89. }