Last active
January 25, 2024 23:00
-
-
Save leanfj/d9472c021d46540923b687fae3fe95fd to your computer and use it in GitHub Desktop.
Exibir query em sql vinda do LINQ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using System.Reflection; | |
using Microsoft.EntityFrameworkCore.Query; | |
using Microsoft.EntityFrameworkCore.Query.Internal; | |
using Microsoft.EntityFrameworkCore.Query.Expressions; | |
using Microsoft.EntityFrameworkCore.Query.Sql; | |
using static Microsoft.EntityFrameworkCore.DbLoggerCategory; | |
has context menu | |
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(Microsoft.EntityFrameworkCore.Storage.Database).GetTypeInfo().DeclaredProperties.Single(x => x.Name == "Dependencies"); | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment