SqliteInterceptor.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Common;
  4. using System.Data.Entity.Infrastructure.Interception;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Threading.Tasks;
  9. namespace XdCxRhDW.Repostory
  10. {
  11. /// <summary>
  12. /// Sqlite拦截器.
  13. /// contains或indexOf成的CHARINDEX函数在sqlite里面并不支持,需要拦截转换成LIKE语句
  14. /// </summary>
  15. public class SqliteInterceptor : DbCommandInterceptor
  16. {
  17. private static Regex replaceRegex = new Regex(@"\(CHARINDEX\((.*?),\s?(.*?)\)\)\s*?>\s*?0");
  18. public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
  19. {
  20. ReplaceCharIndexFunc(command);
  21. }
  22. public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
  23. {
  24. ReplaceCharIndexFunc(command);
  25. }
  26. private void ReplaceCharIndexFunc(DbCommand command)
  27. {
  28. bool isMatch = false;
  29. var text = replaceRegex.Replace(command.CommandText, (match) =>
  30. {
  31. if (match.Success)
  32. {
  33. string paramsKey = match.Groups[1].Value;
  34. string paramsColumnName = match.Groups[2].Value;
  35. //replaceParams
  36. foreach (DbParameter param in command.Parameters)
  37. {
  38. if (param.ParameterName == paramsKey.Substring(1))
  39. {
  40. param.Value = string.Format("%{0}%", param.Value);
  41. break;
  42. }
  43. }
  44. isMatch = true;
  45. return string.Format("{0} LIKE {1}", paramsColumnName, paramsKey);
  46. }
  47. else
  48. return match.Value;
  49. });
  50. if (isMatch)
  51. command.CommandText = text;
  52. }
  53. }
  54. }