zoukankan      html  css  js  c++  java
  • EF Core怎样取得上下文执行查询所生成的SQL语句

    直接上代码:

    using Microsoft.EntityFrameworkCore.Query;
    using Microsoft.EntityFrameworkCore.Query.Internal;
    using Microsoft.EntityFrameworkCore.Storage;
    using System.Linq;
    using System.Reflection;
    
    
    namespace Common.Extension
    {
        public static class QueryableExtensions
        {
            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 = typeof(QueryCompiler).GetTypeInfo().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");
    
            /// <summary>
            /// 获取本次查询SQL语句
            /// </summary>
            /// <typeparam name="TEntity"></typeparam>
            /// <param name="query"></param>
            /// <returns></returns>
            public static string ToSql<TEntity>(this IQueryable<TEntity> query)
            {
                var queryCompiler = (QueryCompiler)QueryCompilerField.GetValue(query.Provider);
                var queryModelGenerator = (QueryModelGenerator)QueryModelGeneratorField.GetValue(queryCompiler);
                var queryModel = queryModelGenerator.ParseQuery(query.Expression);
                var database = 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;
            }
        }
    }

    通过以上代码便可得到EF的执行SQL语句。

    本文转自:https://jhrs.com/2019/28488.html

  • 相关阅读:
    hdu5616 暴力枚举
    codeforce 35C fire again
    常用代码及经验总结(不断更新)
    codeforce AIM tech Round 4 div 2 B rectangles
    codeforce diversity
    codeforce 589B枚举
    codeforces 1A
    自学Java测试代码
    自学Jav测试代码三 Math类 & Date & GregorianCalendar类
    数学类与图形类
  • 原文地址:https://www.cnblogs.com/bluesky0122/p/11048348.html
Copyright © 2011-2022 走看看