首页 > 后端开发 > C++ > 如何从 Entity Framework Core IQueryable 检索 SQL 代码?

如何从 Entity Framework Core IQueryable 检索 SQL 代码?

Mary-Kate Olsen
发布: 2025-01-02 17:11:38
原创
612 人浏览过

How to Retrieve SQL Code from an Entity Framework Core IQueryable?

从 Entity Framework Core IQueryable 获取 SQL 代码

Entity Framework Core 的 ToTraceString 方法,该方法为开发人员提供了由 IQueryable 对象生成的 SQL 代码,在较新的版本中不可用。本文探讨了在 Entity Framework Core 中检索 SQL 代码的替代方法,具体取决于所使用的版本。

EF Core 5/6 (Net 5/6)

在 EF Core 5 和 6 中(Net 5 和 6),ToQueryString 方法可用于获取查询的 SQL 代码:

var query = _context.Widgets.Where(w => w.IsReal && w.Id == 42);  
var sql = query.ToQueryString();
登录后复制

Core 2.1.2

对于旧版本的 Net Core,可以使用自定义扩展方法:

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;

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");
    
        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 Core 3.0

在 EF Core 3.0 中,以下扩展可以使用方法:

        public static string ToSql<TEntity>(this IQueryable<TEntity> query)
        {
            using var enumerator = query.Provider.Execute<IEnumerable<TEntity>>(query.Expression).GetEnumerator();
            var enumeratorType = enumerator.GetType();
            var selectFieldInfo = enumeratorType.GetField(&quot;_selectExpression&quot;, BindingFlags.NonPublic | BindingFlags.Instance) ?? throw new InvalidOperationException($&quot;cannot find field _selectExpression on type {enumeratorType.Name}&quot;);
            var sqlGeneratorFieldInfo = enumeratorType.GetField(&quot;_querySqlGeneratorFactory&quot;, BindingFlags.NonPublic | BindingFlags.Instance) ?? throw new InvalidOperationException($&quot;cannot find field _querySqlGeneratorFactory on type {enumeratorType.Name}&quot;);
            var selectExpression = selectFieldInfo.GetValue(enumerator) as SelectExpression ?? throw new InvalidOperationException($&quot;could not get SelectExpression&quot;);
            var factory = sqlGeneratorFieldInfo.GetValue(enumerator) as IQuerySqlGeneratorFactory ?? throw new InvalidOperationException($&quot;could not get IQuerySqlGeneratorFactory&quot;);
            var sqlGenerator = factory.Create();
            var command = sqlGenerator.GetCommand(selectExpression);
            var sql = command.CommandText;
            return sql;
        }
登录后复制

EF Core 3.1

最后,在 EF Core 3.1 中,可以使用以下扩展方法获取 SQL 代码:

using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Query;

public static string ToSql<TEntity>(this IQueryable<TEntity> query) where TEntity : class
{
    using var enumerator = query.Provider.Execute<IEnumerable<TEntity>>(query.Expression).GetEnumerator();
    var relationalCommandCache = enumerator.Private(&quot;_relationalCommandCache&quot;);
    var selectExpression = relationalCommandCache.Private<SelectExpression>(&quot;_selectExpression&quot;);
    var factory = relationalCommandCache.Private<IQuerySqlGeneratorFactory>(&quot;_querySqlGeneratorFactory&quot;);

    var sqlGenerator = factory.Create();
    var command = sqlGenerator.GetCommand(selectExpression);

    string sql = command.CommandText;
    return sql;
}

private static object Private(this object obj, string privateField) => obj?.GetType().GetField(privateField, BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(obj);
private static T Private<T>(this object obj, string privateField) => (T)obj?.GetType().GetField(privateField, BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(obj);
登录后复制

与在 Entity Framework Core 中公开 ToTraceString 相关的底层问题已由EF 团队预计将在未来版本中解决。

以上是如何从 Entity Framework Core IQueryable 检索 SQL 代码?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板