Skip to content

Instantly share code, notes, and snippets.

@Tirael
Created July 28, 2021 08:29
Show Gist options
  • Save Tirael/e7b9939e9d2ad066abac82b33b816663 to your computer and use it in GitHub Desktop.
Save Tirael/e7b9939e9d2ad066abac82b33b816663 to your computer and use it in GitHub Desktop.
ef to sql
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Storage;
namespace MyNamespace
{
public static class EfUtility
{
public static string ToSql<TEntity>(IQueryable<TEntity> query) where TEntity : class
{
using (IEnumerator<TEntity> enumerator = query.Provider.Execute<IEnumerable<TEntity>>(query.Expression).GetEnumerator())
{
object relationalCommandCache = enumerator.Private("_relationalCommandCache");
SelectExpression selectExpression = relationalCommandCache.Private<SelectExpression>("_selectExpression");
IQuerySqlGeneratorFactory factory = relationalCommandCache.Private<IQuerySqlGeneratorFactory>("_querySqlGeneratorFactory");
QuerySqlGenerator sqlGenerator = factory.Create();
IRelationalCommand 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment