Skip to content

Instantly share code, notes, and snippets.

@dpr-dev
Created July 19, 2020 06:29
Show Gist options
  • Save dpr-dev/dcbf0e41d0438b56bf07946a241fe26b to your computer and use it in GitHub Desktop.
Save dpr-dev/dcbf0e41d0438b56bf07946a241fe26b to your computer and use it in GitHub Desktop.
get sql from ef core 3.1 queryable
public static class IQueryableExtensions
{
public static string ToSql<TEntity>(this IQueryable<TEntity> query) where TEntity : class
{
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();
Microsoft.EntityFrameworkCore.Storage.IRelationalCommand command = sqlGenerator.GetCommand(selectExpression);
return command.CommandText;
}
private static object Private(this object obj, string privateField)
{
return obj?.GetType().GetField(privateField, BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(obj);
}
private static T Private<T>(this object obj, string privateField)
{
return (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