DbExpressionHelper.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using Ant.DbExpressions;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. namespace Ant.SqlServer
  7. {
  8. static class DbExpressionHelper
  9. {
  10. public static DbExpression StripConvert(DbExpression exp)
  11. {
  12. while (exp.NodeType == DbExpressionType.Convert)
  13. {
  14. exp = ((DbConvertExpression)exp).Operand;
  15. }
  16. return exp;
  17. }
  18. public static DbExpression StripInvalidConvert(DbExpression exp)
  19. {
  20. DbConvertExpression convertExpression = exp as DbConvertExpression;
  21. if (convertExpression == null)
  22. return exp;
  23. if (convertExpression.Type.IsEnum)
  24. {
  25. //(enumType)123
  26. if (typeof(int) == convertExpression.Operand.Type)
  27. return StripInvalidConvert(convertExpression.Operand);
  28. DbConvertExpression newExp = new DbConvertExpression(typeof(int), convertExpression.Operand);
  29. return StripInvalidConvert(newExp);
  30. }
  31. Type unType;
  32. //(int?)123
  33. if (Utils.IsNullable(convertExpression.Type, out unType))//可空类型转换
  34. {
  35. if (unType == convertExpression.Operand.Type)
  36. return StripInvalidConvert(convertExpression.Operand);
  37. DbConvertExpression newExp = new DbConvertExpression(unType, convertExpression.Operand);
  38. return StripInvalidConvert(newExp);
  39. }
  40. //(int)enumTypeValue
  41. if (exp.Type == typeof(int))
  42. {
  43. //(int)enumTypeValue
  44. if (convertExpression.Operand.Type.IsEnum)
  45. return StripInvalidConvert(convertExpression.Operand);
  46. //(int)NullableEnumTypeValue
  47. if (Utils.IsNullable(convertExpression.Operand.Type, out unType) && unType.IsEnum)
  48. return StripInvalidConvert(convertExpression.Operand);
  49. }
  50. //float long double and so on
  51. if (exp.Type.IsValueType)
  52. {
  53. //(long)NullableValue
  54. if (Utils.IsNullable(convertExpression.Operand.Type, out unType) && unType == exp.Type)
  55. return StripInvalidConvert(convertExpression.Operand);
  56. }
  57. if (convertExpression.Type == convertExpression.Operand.Type)
  58. {
  59. return StripInvalidConvert(convertExpression.Operand);
  60. }
  61. //如果是子类向父类转换
  62. if (exp.Type.IsAssignableFrom(convertExpression.Operand.Type))
  63. return StripInvalidConvert(convertExpression.Operand);
  64. return convertExpression;
  65. }
  66. }
  67. }