SqliteInterceptor.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 CG.App.EFContext
  10. {
  11. /// <summary>
  12. /// Sqlite拦截器.
  13. /// contains或indexOf成的CHARINDEX函数在sqlite里面并不支持,需要拦截转换成LIKE语句
  14. /// </summary>
  15. public class SqliteInterceptor : IDbCommandInterceptor
  16. {
  17. private static Regex replaceRegex = new Regex(@"\(CHARINDEX\((.*?),\s?(.*?)\)\)\s*?>\s*?0");
  18. public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
  19. {
  20. }
  21. public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
  22. {
  23. }
  24. public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
  25. {
  26. }
  27. public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
  28. {
  29. ReplaceCharIndexFunc(command);
  30. }
  31. public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
  32. {
  33. }
  34. public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
  35. {
  36. ReplaceCharIndexFunc(command);
  37. }
  38. private void ReplaceCharIndexFunc(DbCommand command)
  39. {
  40. bool isMatch = false;
  41. var text = replaceRegex.Replace(command.CommandText, (match) =>
  42. {
  43. if (match.Success)
  44. {
  45. string paramsKey = match.Groups[1].Value;
  46. string paramsColumnName = match.Groups[2].Value;
  47. //replaceParams
  48. foreach (DbParameter param in command.Parameters)
  49. {
  50. if (param.ParameterName == paramsKey.Substring(1))
  51. {
  52. param.Value = string.Format("%{0}%", param.Value);
  53. break;
  54. }
  55. }
  56. isMatch = true;
  57. return string.Format("{0} LIKE {1}", paramsColumnName, paramsKey);
  58. }
  59. else
  60. return match.Value;
  61. });
  62. if (isMatch)
  63. command.CommandText = text;
  64. }
  65. }
  66. }