zoukankan      html  css  js  c++  java
  • 扩展ef core 监视iqueryable生成的sql

    扩展IQueryable

    using Microsoft.EntityFrameworkCore.Query;
    using Microsoft.EntityFrameworkCore.Query.Internal;
    using Microsoft.EntityFrameworkCore.Storage;
    using System.Reflection;
    using System.Linq;
    
    namespace Cy.SmartHospital.Domain.extensions
    {
        public static class IQueryableExtensions
        {
            private static readonly TypeInfo QueryCompilerTypeInfo = typeof(QueryCompiler).GetTypeInfo();
    
            private static readonly FieldInfo QueryCompilerField = typeof(EntityQueryProvider).GetTypeInfo().DeclaredFields.First(x => x.Name == "_queryCompiler");
    
            private static readonly FieldInfo QueryModelGeneratorField = QueryCompilerTypeInfo.DeclaredFields.First(x => x.Name == "_queryModelGenerator");
    
            private static readonly FieldInfo DataBaseField = QueryCompilerTypeInfo.DeclaredFields.Single(x => x.Name == "_database");
    
            private static readonly PropertyInfo DatabaseDependenciesField = typeof(Database).GetTypeInfo().DeclaredProperties.Single(x => x.Name == "Dependencies");
    
            public static string ToSql<TEntity>(this IQueryable<TEntity> query) where TEntity : class
            {
                var queryCompiler = (QueryCompiler)QueryCompilerField.GetValue(query.Provider);
                var modelGenerator = (QueryModelGenerator)QueryModelGeneratorField.GetValue(queryCompiler);
                var queryModel = modelGenerator.ParseQuery(query.Expression);
                var database = (IDatabase)DataBaseField.GetValue(queryCompiler);
                var databaseDependencies = (DatabaseDependencies)DatabaseDependenciesField.GetValue(database);
                var queryCompilationContext = databaseDependencies.QueryCompilationContextFactory.Create(false);
                var modelVisitor = (RelationalQueryModelVisitor)queryCompilationContext.CreateQueryModelVisitor();
                modelVisitor.CreateQueryExecutor<TEntity>(queryModel);
                var sql = modelVisitor.Queries.First().ToString();
    
                return sql;
            }
        }
    }
    
    
  • 相关阅读:
    Orchard CMS中如何打包不带源码的模块
    牛X的CSS3
    Docker指令
    Spring Boot 应用 发布到Docker
    Haproxy全透明代理
    TCP/IP协议理解
    ubuntu tomcat 部署java web
    UDP"打洞"原理
    java多线程-线程通信
    window环境下杀死tomcat
  • 原文地址:https://www.cnblogs.com/cqxhl/p/12993284.html
Copyright © 2011-2022 走看看