SelectModelToSql.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. using System.Linq;
  6. namespace SqlSugar
  7. {
  8. public abstract partial class SqlBuilderProvider : SqlBuilderAccessory, ISqlBuilder
  9. {
  10. public KeyValuePair<string, SugarParameter[]> SelectModelToSql(List<SelectModel> models)
  11. {
  12. StringBuilder sql = new StringBuilder("");
  13. var pars = new List<SugarParameter> { };
  14. foreach (var item in models)
  15. {
  16. if (item is SelectModel)
  17. {
  18. var orderByModel = item as SelectModel;
  19. orderByModel.AsName=GetAsName(orderByModel);
  20. orderByModel.FieldName = GetSqlPart(orderByModel.FieldName, pars).ObjToString();
  21. AppendFiledName(sql, orderByModel);
  22. }
  23. else
  24. {
  25. }
  26. }
  27. return new KeyValuePair<string, SugarParameter[]>(sql.ToString().TrimEnd(','), pars.ToArray());
  28. }
  29. private string GetAsName(SelectModel orderByModel)
  30. {
  31. if (orderByModel.AsName.IsNullOrEmpty())
  32. {
  33. orderByModel.AsName = orderByModel.FieldName.ObjToString();
  34. }
  35. if (orderByModel.AsName.StartsWith(UtilConstants.ReplaceKey))
  36. {
  37. return orderByModel.AsName.Replace(UtilConstants.ReplaceKey, string.Empty);
  38. }
  39. if (orderByModel.AsName?.Contains("[")==true)
  40. {
  41. orderByModel.AsName = orderByModel.AsName.Trim('[').Trim(']');
  42. return this.SqlTranslationLeft + orderByModel.AsName + this.SqlTranslationRight;
  43. }
  44. if (this.SqlTranslationLeft != null && orderByModel.AsName?.Contains(this.SqlTranslationLeft) == true)
  45. {
  46. return orderByModel.AsName;
  47. }
  48. return this.SqlTranslationLeft + orderByModel.AsName + this.SqlTranslationRight;
  49. }
  50. private void AppendFiledName(StringBuilder sql, SelectModel orderByModel)
  51. {
  52. sql.Append($" {orderByModel.FieldName} AS {orderByModel.AsName} ,");
  53. }
  54. }
  55. }