public static string ToSql<TEntity>(this IQueryable<TEntity> query, DbContext dbCtx)
{
var modelGenerator = dbCtx.GetService<IQueryModelGenerator>();
var queryModel = modelGenerator.ParseQuery(query.Expression);
var databaseDependencies = dbCtx.GetService<DatabaseDependencies>();
var queryCompilationContext = databaseDependencies.QueryCompilationContextFactory.Create(false);
var modelVisitor = (RelationalQueryModelVisitor)queryCompilationContext.CreateQueryModelVisitor();
modelVisitor.CreateQueryExecutor<TEntity>(queryModel);
var sqlList = modelVisitor.Queries.ToList();
// modelVisitor.Queries.First().ToString();
var sql = "";
foreach (var i in sqlList) {
sql += i.ToString() + ";";
}
return sql;
}
写一个拓展方法
然后直接用就行了
var ce2 = _dbContextProvider.GetDbContext();
var ce = all.PageBy(input).ToSql(ce2);