一.利用反射生成查詢語句 該方法轉載自:https://jhrs.com/2019/28488.html 使用方法 效果 備註:該擴展貌似只能應用於EF查詢方法,我嘗試過各種重寫方法,仍然不能完美的生成真實執行的Sql語句,如果哪位高人有辦法做到請在評論區指導一下。 二、Microsoft.Exte ...
一.利用反射生成查詢語句
該方法轉載自:https://jhrs.com/2019/28488.html
using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.Internal; using Microsoft.EntityFrameworkCore.Storage; using System.Linq; using System.Reflection; namespace Common.Standard.EFCore { 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; } } }
使用方法
var ss = _context.UserTable.Where(m => m.UserName == "admin"); string sql = ss.ToSql();
效果
備註:該擴展貌似只能應用於EF查詢方法,我嘗試過各種重寫方法,仍然不能完美的生成真實執行的Sql語句,如果哪位高人有辦法做到請在評論區指導一下。
二、Microsoft.Extensions.Logging.Debug在控制台輸出完整調試日誌
這種方法是比較推薦的,可以完整的輸出EF生成的SQL語句
1.用NuGet管理器添加Microsoft.Extensions.Logging.Debug包
2.修改DbContext類
public partial class MyDbnContext : DbContext { [Obsolete] public static readonly LoggerFactory LoggerFactory = new LoggerFactory(new[] { new DebugLoggerProvider((_, __) => true) }); ... ... protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseLoggerFactory(LoggerFactory); } ... ... }
3.在想要查看sql的db.SaveChanges()方法上加斷點,然後調試程式。
4.點擊VisualStudio工具條:調試->視窗->輸出,打開輸出日誌,並搜索EntityFrameworkCore,結果如下
紅框內圈出的就是完整的SQL輸出
參考項目: