QueryableExtensions.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using Microsoft.EntityFrameworkCore.Query;
  2. using Microsoft.EntityFrameworkCore.Query.Internal;
  3. using Microsoft.EntityFrameworkCore.Storage;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text;
  9. namespace YLShipBuildLandMap.Entity.Extensions
  10. {
  11. public static class QueryableExtensions
  12. {
  13. private static readonly TypeInfo QueryCompilerTypeInfo = typeof(QueryCompiler).GetTypeInfo();
  14. private static readonly FieldInfo QueryCompilerField = typeof(EntityQueryProvider).GetTypeInfo().DeclaredFields.First(x => x.Name == "_queryCompiler");
  15. private static readonly FieldInfo QueryModelGeneratorField = typeof(QueryCompiler).GetTypeInfo().DeclaredFields.First(x => x.Name == "_queryModelGenerator");
  16. private static readonly FieldInfo DataBaseField = QueryCompilerTypeInfo.DeclaredFields.Single(x => x.Name == "_database");
  17. private static readonly PropertyInfo DatabaseDependenciesField = typeof(Microsoft.EntityFrameworkCore.Storage.Database).GetTypeInfo().DeclaredProperties.Single(x => x.Name == "Dependencies");
  18. /// <summary>
  19. /// 获取本次查询SQL语句
  20. /// </summary>
  21. /// <typeparam name="TEntity"></typeparam>
  22. /// <param name="query"></param>
  23. /// <returns></returns>
  24. /*public static string ToSql<TEntity>(this IQueryable<TEntity> query)
  25. {
  26. var queryCompiler = (QueryCompiler)QueryCompilerField.GetValue(query.Provider);
  27. var queryModelGenerator = (QueryModelGenerator)QueryModelGeneratorField.GetValue(queryCompiler);
  28. var queryModel = queryModelGenerator.ParseQuery(query.Expression);
  29. var database = DataBaseField.GetValue(queryCompiler);
  30. var databaseDependencies = (DatabaseDependencies)DatabaseDependenciesField.GetValue(database);
  31. var queryCompilationContext = databaseDependencies.QueryCompilationContextFactory.Create(false);
  32. var modelVisitor = (RelationalQueryModelVisitor)queryCompilationContext.CreateQueryModelVisitor();
  33. modelVisitor.CreateQueryExecutor<TEntity>(queryModel);
  34. var sql = modelVisitor.Queries.First().ToString();
  35. return sql;
  36. }*/
  37. }
  38. }