SubWhereIF.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. namespace SqlSugar
  8. {
  9. public class SubWhereIF : ISubOperation
  10. {
  11. public bool HasWhere
  12. {
  13. get; set;
  14. }
  15. public string Name
  16. {
  17. get { return "WhereIF"; }
  18. }
  19. public Expression Expression
  20. {
  21. get; set;
  22. }
  23. public int Sort
  24. {
  25. get
  26. {
  27. return 400;
  28. }
  29. }
  30. public ExpressionContext Context
  31. {
  32. get; set;
  33. }
  34. public string GetValue(Expression expression)
  35. {
  36. var exp = expression as MethodCallExpression;
  37. object value = null;
  38. try
  39. {
  40. value = ExpressionTool.DynamicInvoke(exp.Arguments[0]);
  41. }
  42. catch
  43. {
  44. Check.Exception(true, ErrorMessage.WhereIFCheck,exp.Arguments[0].ToString());
  45. }
  46. if (Regex.Matches(expression.ToString(), "Subqueryable").Count >= 2)
  47. {
  48. new SubSelect() { Context = this.Context }.SetShortNameNext(exp, "+");
  49. }
  50. var isWhere= Convert.ToBoolean(value);
  51. if (!Convert.ToBoolean(isWhere)) {
  52. return "WHERE 1=1 ";
  53. }
  54. var argExp = exp.Arguments[1];
  55. var copyContext = this.Context;
  56. if (this.Context.JoinIndex > 0)
  57. {
  58. copyContext = this.Context.GetCopyContextWithMapping();
  59. copyContext.IsSingle = false;
  60. }
  61. var result = "WHERE " + SubTools.GetMethodValue(copyContext, argExp, ResolveExpressType.WhereMultiple);
  62. if (this.Context.JoinIndex > 0)
  63. {
  64. this.Context.Parameters.AddRange(copyContext.Parameters);
  65. this.Context.Index = copyContext.Index;
  66. this.Context.ParameterIndex = copyContext.ParameterIndex;
  67. }
  68. var selfParameterName = Context.GetTranslationColumnName((argExp as LambdaExpression).Parameters.First().Name) + UtilConstants.Dot;
  69. if (this.Context.JoinIndex == 0)
  70. result = result.Replace(selfParameterName, SubTools.GetSubReplace(this.Context));
  71. if (!string.IsNullOrEmpty(selfParameterName) && this.Context.IsSingle && this.Context.JoinIndex == 0)
  72. {
  73. this.Context.CurrentShortName = selfParameterName.TrimEnd('.');
  74. }
  75. return result;
  76. }
  77. }
  78. }