How to View SQL Generated by Entity Framework Core IQueryable
Question:
In Entity Framework Core, how do you access the SQL code generated by an IQueryable object? The ToTraceString() method, available in previous versions, is not present in EF Core.
Answer:
EF Core 5/6 / Net 5/6
For EF Core 5 and 6 with .NET 5 and 6, you can use the ToQueryString() method:
var query = _context.Widgets.Where(w => w.IsReal && w.Id == 42); var sql = query.ToQueryString();
For older versions of .NET Core, an extension method can be used:
Core 2.1.2
public static string ToSql<TEntity>(this IQueryable<TEntity> query) { // Reflection and casting voodoo to get EF internal classes var sql = ...; return sql; }
EF Core 3.0
public static string ToSql<TEntity>(this IQueryable<TEntity> query) { using (var enumerator = query.Provider.Execute<IEnumerable<TEntity>>(query.Expression).GetEnumerator()) { // More reflection and casting voodoo var sql = ...; return sql; } }
EF Core 3.1
public static string ToSql<TEntity>(this IQueryable<TEntity> query) where TEntity : class { using (var enumerator = query.Provider.Execute<IEnumerable<TEntity>>(query.Expression).GetEnumerator()) { // Even more reflection and casting voodoo var sql = ...; return sql; } }
Note:
For EF Core versions prior to 5, reflection is necessary to retrieve the SQL generated by an IQueryable.
The above is the detailed content of How Do I View the SQL Generated by Entity Framework Core IQueryable?. For more information, please follow other related articles on the PHP Chinese website!