You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.6 KiB

2 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using SqlSugar;
  6. using OrmTest.Models;
  7. namespace OrmTest.Demo
  8. {
  9. public class ExtSqlFun : DemoBase
  10. {
  11. public static SqlSugarClient GetDb()
  12. {
  13. //Create ext method
  14. var expMethods = new List<SqlFuncExternal>();
  15. expMethods.Add(new SqlFuncExternal()
  16. {
  17. UniqueMethodName = "MyToString",
  18. MethodValue = (expInfo, dbType, expContext) =>
  19. {
  20. return string.Format("CAST({0} AS VARCHAR(MAX))", expInfo.Args[0].MemberName);
  21. }
  22. });
  23. var config = new ConnectionConfig()
  24. {
  25. ConnectionString = Config.ConnectionString,
  26. DbType = DbType.SqlServer,
  27. IsAutoCloseConnection = true,
  28. ConfigureExternalServices = new ConfigureExternalServices()
  29. {
  30. SqlFuncServices = expMethods//set ext method
  31. }
  32. };
  33. SqlSugarClient db = new SqlSugarClient(config);
  34. return db;
  35. }
  36. public static string MyToString<T>(T str)
  37. {
  38. throw new NotSupportedException("Can only be used in expressions");
  39. }
  40. public static void Init()
  41. {
  42. var db = GetDb();
  43. var list = db.Queryable<Student>().Where(it => MyToString(it.Id) == "1302583").ToList();
  44. var sql = db.Queryable<Student>().Where(it => MyToString(it.Id) == "1302583").ToSql();
  45. Console.WriteLine(sql);
  46. }
  47. }
  48. }