See the SQL Generated by EF Core (ToQueryString and Logging)

Want the short answer to EF Core how to see generated SQL? Call ToQueryString() on the query and print it:

var query = db.Orders.Where(o => o.Total >= minTotal);
Console.WriteLine(query.ToQueryString());

That prints the SELECT plus a DECLARE line for each parameter, and it doesn’t touch the database. To see every command your app really sends, including SaveChanges, turn on LogTo. I tested six ways on .NET 10, EF Core 10.0.14 and SQL Server 2025.

Every Way to See EF Core Generated SQL

Each row is a section below, run against the same small orders database on .NET 10:

MethodShowsBest for
ToQueryString()SQL for one query, without running itQuick checks while you write LINQ
LogTo(Console.WriteLine, ...)Every command EF Core executesConsole apps and local debugging
EnableSensitiveDataLogging()Parameter values in the logDevelopment only
TagWith() / TagWithCallSite()A comment at the top of the SQLFinding a query in logs and SQL Server
DbCommandInterceptorThe DbCommand itself, plus timingCustom slow-query logging
appsettings.json log levelCommands through ILoggerASP.NET Core apps

The Sample Project: EF Core 10 and SQL Server

If you’re new to DbContext and migrations, start with my EF Core tutorial for beginners; this post assumes you have a context that works. My demo is one Web SDK project, so the console demos and the ASP.NET Core one share the same model:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.14" />
    <PackageReference Include="System.Security.Cryptography.Pkcs" Version="10.0.14" />
  </ItemGroup>

</Project>

The Pkcs reference clears an NU1903 warning about the older System.Security.Cryptography.Pkcs that the SQL Server provider pulls in.

The model is two tables: customers in four US cities, and their 2026 orders in USD, with a DateOnly order date:

namespace W12EfSql;

public class Customer
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public required string City { get; set; }
    public required string State { get; set; }
    public List<Order> Orders { get; } = [];
}

public class Order
{
    public int Id { get; set; }
    public DateOnly OrderDate { get; set; }
    public decimal Total { get; set; }
    public int CustomerId { get; set; }
    public Customer Customer { get; set; } = null!;
}

The context takes its options through a primary constructor, so each demo can add its own logging. Create() is a small helper for the console demos:

using Microsoft.EntityFrameworkCore;

namespace W12EfSql;

public class ShopDb(DbContextOptions<ShopDb> options) : DbContext(options)
{
    public const string ConnectionString =
        "Server=.;Database=w12_efsql;Trusted_Connection=True;TrustServerCertificate=True";

    public DbSet<Customer> Customers => Set<Customer>();
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Property(c => c.State).HasMaxLength(2);
        modelBuilder.Entity<Order>().Property(o => o.Total).HasPrecision(10, 2);
    }

    // console demos: one context with whatever extra options the demo needs
    public static ShopDb Create(Action<DbContextOptionsBuilder<ShopDb>>? configure = null)
    {
        var builder = new DbContextOptionsBuilder<ShopDb>().UseSqlServer(ConnectionString);
        configure?.Invoke(builder);
        return new ShopDb(builder.Options);
    }
}

Program.cs runs one demo per argument, and Seed.cs rebuilds the database with five orders:

using System.Globalization;
using W12EfSql;

CultureInfo.CurrentCulture = new CultureInfo("en-US");   // log timestamps in US format

switch (args.FirstOrDefault())
{
    case "seed": await Seed.RunAsync(); break;
    case "tostring": QueryStringDemo.Run(); break;
    case "terminal": await TerminalDemo.RunAsync(); break;
    case "logto": await LogToDemo.RunAsync(); break;
    case "sensitive": await SensitiveDemo.RunAsync(); break;
    case "save": await SaveDemo.RunAsync(); break;
    case "tags": await TagsDemo.RunAsync(); break;
    case "intercept": await InterceptDemo.RunAsync(); break;
    case "web": await WebDemo.RunAsync(); break;
    default: Console.WriteLine("Pass a demo name, for example: dotnet run -- logto"); break;
}
using Microsoft.EntityFrameworkCore;

namespace W12EfSql;

public static class Seed
{
    public static async Task RunAsync()
    {
        using var db = ShopDb.Create();
        db.Database.SetCommandTimeout(TimeSpan.FromMinutes(3));   // CREATE DATABASE can be slow
        await db.Database.EnsureDeletedAsync();
        await db.Database.EnsureCreatedAsync();

        var jenna = new Customer { Name = "Jenna Morales", City = "Austin", State = "TX" };
        jenna.Orders.Add(new Order { OrderDate = new(2026, 10, 3), Total = 489.99m });
        jenna.Orders.Add(new Order { OrderDate = new(2026, 10, 21), Total = 129.50m });
        var tyler = new Customer { Name = "Tyler Brooks", City = "Denver", State = "CO" };
        tyler.Orders.Add(new Order { OrderDate = new(2026, 10, 9), Total = 312.00m });
        var hannah = new Customer { Name = "Hannah Price", City = "Columbus", State = "OH" };
        hannah.Orders.Add(new Order { OrderDate = new(2026, 10, 14), Total = 74.25m });
        var marcus = new Customer { Name = "Marcus Reed", City = "Houston", State = "TX" };
        marcus.Orders.Add(new Order { OrderDate = new(2026, 11, 2), Total = 268.40m });

        db.Customers.AddRange(jenna, tyler, hannah, marcus);
        Console.WriteLine($"Seeded {await db.SaveChangesAsync()} rows into w12_efsql");
    }
}

Run dotnet run -- seed once. It printed Seeded 9 rows into w12_efsql: four customers plus five orders. EnsureCreatedAsync keeps the demo short; a real app should create its schema with EF Core migrations.

ToQueryString: Get the SQL Query for a LINQ Query

ToQueryString() works on any IQueryable that EF Core can translate. This one filters by a minimum total and a list of states, then projects three columns, the kind of LINQ query you’d write for a report:

using Microsoft.EntityFrameworkCore;

namespace W12EfSql;

public static class QueryStringDemo
{
    public static void Run()
    {
        using var db = ShopDb.Create();
        decimal minTotal = 250m;
        string[] states = ["TX", "CO"];

        var query = db.Orders
            .Where(o => o.Total >= minTotal && states.Contains(o.Customer.State))
            .OrderByDescending(o => o.Total)
            .Select(o => new { o.Id, o.Customer.Name, o.Total });

        Console.WriteLine(query.ToQueryString());
    }
}
EF Core ToQueryString in VS Code: QueryStringDemo.cs filters orders by total and state, and the terminal prints the generated SQL with DECLARE lines for @minTotal, @states1 and @states2
ToQueryString prints the SELECT and a DECLARE line per parameter

Output:

DECLARE @minTotal decimal(10,2) = 250.0;
DECLARE @states1 nvarchar(2) = N'TX';
DECLARE @states2 nvarchar(2) = N'CO';

SELECT [o].[Id], [c].[Name], [o].[Total]
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [o].[Total] >= @minTotal AND [c].[State] IN (@states1, @states2)
ORDER BY [o].[Total] DESC

The local variable minTotal became the parameter @minTotal, and the DECLARE lines carry the real values, so you can paste the whole thing into SSMS and run it. It’s also handy in an xUnit test that asserts a query keeps its WHERE clause.

Notice the names, too. EF Core 10 simplified them (older versions printed @__minTotal_0), and states.Contains() now becomes one parameter per value, @states1 and @states2. EF Core 8 and 9 sent the list as a single JSON parameter with OPENJSON.

Why Doesn’t ToQueryString Show the SQL for First or Count?

Because First(), Count() and Sum() run the query right away and return a value, not an IQueryable. db.Orders.Count() is an int, so there’s nothing to call ToQueryString() on.

The catch is that these operators change the SQL. To prove it, I printed ToQueryString() for a Texas filter, then ran FirstAsync and CountAsync on the same query with logging on:

The square brackets around the category name are a collection expression; that overload of LogTo logs only the categories you list, here just the SQL commands.

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace W12EfSql;

public static class TerminalDemo
{
    public static async Task RunAsync()
    {
        using var db = ShopDb.Create(o => o.LogTo(Console.WriteLine,
            [DbLoggerCategory.Database.Command.Name], LogLevel.Information,
            DbContextLoggerOptions.None));
        var texas = db.Orders.Where(o => o.Customer.State == "TX");

        Console.WriteLine("ToQueryString:\n" + texas.ToQueryString() + "\n");
        var first = await texas.OrderBy(o => o.OrderDate).FirstAsync();
        int count = await texas.CountAsync();
        Console.WriteLine($"\nFirst: {first.Total:C}, Count: {count}");
    }
}

Output:

ToQueryString:
SELECT [o].[Id], [o].[CustomerId], [o].[OrderDate], [o].[Total]
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [c].[State] = N'TX'

Executed DbCommand (62ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT TOP(1) [o].[Id], [o].[CustomerId], [o].[OrderDate], [o].[Total]
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [c].[State] = N'TX'
ORDER BY [o].[OrderDate]
Executed DbCommand (10ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*)
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [c].[State] = N'TX'

First: $489.99, Count: 3

The ToQueryString SQL has no TOP(1) and no ORDER BY, while the logged FirstAsync query has both, and CountAsync became SELECT COUNT(*). Only two Executed DbCommand entries appear, so ToQueryString() itself never hit SQL Server.

The literal "TX" in the lambda stayed a constant, N'TX', while a variable becomes a parameter. The run returned $489.99 for the first order and 3 Texas orders. SaveChanges has the same limit: it isn’t a query, so only logging shows its SQL.

Log the Generated SQL with LogTo (Simple Logging)

Simple logging needs no extra package. The one-liner is optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information); without a level, EF Core logs everything at Debug and up, which is a lot. I also passed DbContextLoggerOptions flags to drop the timestamp, which follows the current culture (see C# DateTime formats):

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace W12EfSql;

public static class LogToDemo
{
    public static async Task RunAsync()
    {
        using var db = ShopDb.Create(o => o.LogTo(Console.WriteLine, LogLevel.Information,
            DbContextLoggerOptions.Level | DbContextLoggerOptions.Id | DbContextLoggerOptions.Category));

        decimal minTotal = 250m;
        var bigOrders = await db.Orders
            .Where(o => o.Total >= minTotal)
            .ToListAsync();

        Console.WriteLine($"Orders over {minTotal:C}: {bigOrders.Count}");
    }
}
EF Core LogTo in VS Code: LogToDemo.cs logs to Console.WriteLine at LogLevel.Information, and the terminal shows RelationalEventId.CommandExecuted with Executed DbCommand and the SELECT
LogTo prints one Executed DbCommand entry per SQL statement

Output:

info: RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command) 
      Executed DbCommand (52ms) [Parameters=[@minTotal='?' (Precision = 10) (Scale = 2) (DbType = Decimal)], CommandType='Text', CommandTimeout='30']
      SELECT [o].[Id], [o].[CustomerId], [o].[OrderDate], [o].[Total]
      FROM [Orders] AS [o]
      WHERE [o].[Total] >= @minTotal
Orders over $250.00: 3

Each entry starts with the level, the event ID (RelationalEventId.CommandExecuted[20101]) and the category, then the duration, the parameters and the SQL. The query found 3 orders of $250 or more.

Note: the '?' isn’t a bug. EF Core hides parameter values by default; the sensitive data section below turns them on.

Show Parameter Values with EnableSensitiveDataLogging

EnableSensitiveDataLogging() puts the real parameter values in the log. EnableDetailedErrors() is its usual partner: it wraps each column read in a try-catch so a NULL-in-a-required-column error names the property:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace W12EfSql;

public static class SensitiveDemo
{
    public static async Task RunAsync()
    {
        using var db = ShopDb.Create(o => o
            .LogTo(Console.WriteLine, [DbLoggerCategory.Database.Command.Name], LogLevel.Information,
                DbContextLoggerOptions.None)
            .EnableSensitiveDataLogging()     // development only: logs parameter values
            .EnableDetailedErrors());

        decimal minTotal = 250m;
        var bigOrders = await db.Orders
            .Where(o => o.Total >= minTotal)
            .ToListAsync();

        Console.WriteLine($"Orders over {minTotal:C}: {bigOrders.Count}");
    }
}
EF Core EnableSensitiveDataLogging in VS Code: SensitiveDemo.cs adds EnableSensitiveDataLogging and EnableDetailedErrors, and the log shows the real @minTotal parameter value instead of a question mark
With sensitive data logging on, the parameter value shows up in the log

Output:

Executed DbCommand (52ms) [Parameters=[@minTotal='250' (Precision = 10) (Scale = 2)], CommandType='Text', CommandTimeout='30']
SELECT [o].[Id], [o].[CustomerId], [o].[OrderDate], [o].[Total]
FROM [Orders] AS [o]
WHERE [o].[Total] >= @minTotal
Orders over $250.00: 3

Now the log says @minTotal='250' instead of '?'. That’s exactly what you need when a query returns the wrong rows.

Important: never ship this to production. Parameter values are customer names, emails and IDs. EF Core 10 also redacts constants it inlines into the SQL (they log as ?), and this switch turns those back on too.

See the SQL That SaveChanges Generates

Inserts, updates and deletes don’t have a query to call ToQueryString() on, so logging is the only way in. This demo updates one of Hannah Price’s orders and adds two new ones:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace W12EfSql;

public static class SaveDemo
{
    public static async Task RunAsync()
    {
        using var db = ShopDb.Create(o => o
            .LogTo(Console.WriteLine, [DbLoggerCategory.Database.Command.Name], LogLevel.Information,
                DbContextLoggerOptions.None)
            .EnableSensitiveDataLogging());

        var hannah = await db.Customers.Include(c => c.Orders).SingleAsync(c => c.Name == "Hannah Price");
        hannah.Orders[0].Total = 79.25m;                                   // UPDATE
        hannah.Orders.Add(new Order { OrderDate = new(2026, 11, 5), Total = 58.00m });   // INSERT
        hannah.Orders.Add(new Order { OrderDate = new(2026, 11, 6), Total = 112.75m });  // INSERT

        Console.WriteLine($"Saved {await db.SaveChangesAsync()} rows");
    }
}
EF Core SaveChanges SQL in VS Code: SaveDemo.cs updates one order and adds two, and the log shows one batch with UPDATE Orders OUTPUT 1 and MERGE Orders with OUTPUT INSERTED.Id
One SaveChangesAsync call sent the UPDATE and both INSERTs in a single batch

Output:

Executed DbCommand (68ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [c0].[Id], [c0].[City], [c0].[Name], [c0].[State], [o].[Id], [o].[CustomerId], [o].[OrderDate], [o].[Total]
FROM (
    SELECT TOP(2) [c].[Id], [c].[City], [c].[Name], [c].[State]
    FROM [Customers] AS [c]
    WHERE [c].[Name] = N'Hannah Price'
) AS [c0]
LEFT JOIN [Orders] AS [o] ON [c0].[Id] = [o].[CustomerId]
ORDER BY [c0].[Id]
Executed DbCommand (42ms) [Parameters=[@p1='4', @p0='79.25' (Precision = 10) (Scale = 2), @p2='3', @p3='11/05/2026' (DbType = Date), @p4='58.00' (Precision = 10) (Scale = 2), @p5='3', @p6='11/06/2026' (DbType = Date), @p7='112.75' (Precision = 10) (Scale = 2)], CommandType='Text', CommandTimeout='30']
SET NOCOUNT ON;
UPDATE [Orders] SET [Total] = @p0
OUTPUT 1
WHERE [Id] = @p1;
MERGE [Orders] USING (
VALUES (@p2, @p3, @p4, 0),
(@p5, @p6, @p7, 1)) AS i ([CustomerId], [OrderDate], [Total], _Position) ON 1=0
WHEN NOT MATCHED THEN
INSERT ([CustomerId], [OrderDate], [Total])
VALUES (i.[CustomerId], i.[OrderDate], i.[Total])
OUTPUT INSERTED.[Id], i._Position;
Saved 3 rows

The first command is the Include load. The second is the whole save in one round trip: an UPDATE for the changed total, then a MERGE that inserts both orders and returns their new keys with OUTPUT INSERTED.[Id]. SaveChangesAsync reported 3 rows.

EF Core uses MERGE here so it can match each generated Id back to the right object through _Position. For the endpoint side of saving data, see my ASP.NET Core Web API CRUD with EF Core post.

Tag EF Core Queries with TagWith and TagWithCallSite

In a busy log, every SELECT looks the same. TagWith() adds your own comment to the SQL, and TagWithCallSite() adds the file name and line number where the query was written:

using Microsoft.EntityFrameworkCore;

namespace W12EfSql;

public static class TagsDemo
{
    public static async Task RunAsync()
    {
        using var db = ShopDb.Create();
        decimal minTotal = 250m;

        var query = db.Orders
            .TagWith("Sales dashboard: Texas orders over $250")
            .TagWithCallSite()
            .Where(o => o.Customer.State == "TX" && o.Total >= minTotal);

        Console.WriteLine(query.ToQueryString());
        Console.WriteLine($"\nRows: {(await query.ToListAsync()).Count}");
    }
}
EF Core TagWith and TagWithCallSite in VS Code: TagsDemo.cs tags a Texas orders query, and ToQueryString shows the SQL comment lines Sales dashboard and File TagsDemo.cs line number
Query tags become SQL comments at the top of the command

Output:

DECLARE @minTotal decimal(10,2) = 250.0;

-- Sales dashboard: Texas orders over $250
-- File: C:\DotNetDemo\W12EfSql\TagsDemo.cs:14

SELECT [o].[Id], [o].[CustomerId], [o].[OrderDate], [o].[Total]
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [c].[State] = N'TX' AND [o].[Total] >= @minTotal

Rows: 2

Both tags became -- comments above the SELECT, and they travel with the command, so they show up in the log, in ToQueryString() and on SQL Server. The query returned 2 rows.

Tags are always literal strings in the SQL, so don’t put values that change per call in them.

Find an EF Core Query in SQL Server

Sometimes the app isn’t yours to change. SQL Server keeps statistics for cached plans, and the tag makes our query easy to find. After the tags demo ran, I asked sys.dm_exec_query_stats:

sqlcmd -S . -E -d w12_efsql -W -Q "SET NOCOUNT ON; SELECT qs.execution_count, LEFT(REPLACE(REPLACE(st.text, CHAR(13), ''), CHAR(10), ' '), 70) AS sql_text FROM sys.dm_exec_query_stats AS qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st WHERE st.text LIKE '%Sales dashboard%' AND st.text NOT LIKE '%dm_exec%'"
execution_count sql_text
--------------- --------
1 (@minTotal decimal(10,2))-- Sales dashboard: Texas orders over $250 --

The text starts with (@minTotal decimal(10,2)) because EF Core sends parameterized SQL through sp_executesql, and execution_count tells you how many times that cached plan ran. You need the VIEW SERVER STATE permission to read these views.

For a live trace, use an Extended Events session on the sql_batch_completed and rpc_completed events (SSMS has an XEvent Profiler node for this). SQL Server Profiler still opens, but Microsoft lists SQL Trace and Profiler as deprecated.

Log SQL with a DbCommandInterceptor

An interceptor sees the actual DbCommand before or after it runs. For plain logging, Microsoft says LogTo is the better fit, but an interceptor is handy for your own format, timing or a slow-query alert. ReaderExecutedAsync runs after each awaited query:

using System.Data.Common;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace W12EfSql;

public class SqlTimingInterceptor : DbCommandInterceptor
{
    public override ValueTask<DbDataReader> ReaderExecutedAsync(DbCommand command,
        CommandExecutedEventData eventData, DbDataReader result, CancellationToken cancellationToken = default)
    {
        string firstLine = command.CommandText.Split('\n')[0].Trim();
        Console.WriteLine($"[SQL {eventData.Duration.TotalMilliseconds:F0} ms] {firstLine} ...");
        return base.ReaderExecutedAsync(command, eventData, result, cancellationToken);
    }
}

The interceptor holds no state, so one instance can serve every context. Pass the CancellationToken through to the base call, then register it with AddInterceptors:

using Microsoft.EntityFrameworkCore;

namespace W12EfSql;

public static class InterceptDemo
{
    static readonly SqlTimingInterceptor Timing = new();   // stateless: one instance for every context

    public static async Task RunAsync()
    {
        using var db = ShopDb.Create(o => o.AddInterceptors(Timing));

        var customers = await db.Customers.OrderBy(c => c.Name).ToListAsync();
        var total = await db.Orders.SumAsync(o => o.Total);
        Console.WriteLine($"{customers.Count} customers, {total:C} in orders");
    }
}

Output:

[SQL 61 ms] SELECT [c].[Id], [c].[City], [c].[Name], [c].[State] ...
[SQL 8 ms] SELECT COALESCE(SUM([o].[Total]), 0.0) ...
4 customers, $1,449.89 in orders

Each query printed its time and first SQL line (4 customers, $1,449.89 in orders); times vary from run to run. To flag slow queries, compare eventData.Duration with a threshold.

How Do You Log EF Core SQL in ASP.NET Core?

In ASP.NET Core you don’t need LogTo. AddDbContext registers a scoped context and hands EF Core the app’s logger factory, so the SQL is controlled by the Logging:LogLevel section in appsettings.json:

{
  "Urls": "http://localhost:5904",
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  }
}

Default is Warning to keep the demo quiet, and the more specific Microsoft.EntityFrameworkCore.Database.Command category wins for SQL. The minimal API below starts on port 5904, calls itself once with HttpClient and stops:

using Microsoft.EntityFrameworkCore;

namespace W12EfSql;

public static class WebDemo
{
    public static async Task RunAsync()
    {
        var builder = WebApplication.CreateBuilder();
        builder.Services.AddDbContext<ShopDb>(o => o.UseSqlServer(ShopDb.ConnectionString));
        var app = builder.Build();

        app.MapGet("/orders/{state}", (string state, ShopDb db) =>
            db.Orders.Where(o => o.Customer.State == state).Select(o => o.Total).ToListAsync());

        await app.StartAsync();
        using var http = new HttpClient();
        Console.WriteLine(await http.GetStringAsync("http://localhost:5904/orders/TX"));
        await app.StopAsync();
    }
}
ASP.NET Core EF Core SQL logging in VS Code: WebDemo.cs registers AddDbContext with a minimal API, and the console logger prints Microsoft.EntityFrameworkCore.Database.Command Executed DbCommand from appsettings.json
appsettings.json turned on the Database.Command category; no LogTo in the code

Output:

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (48ms) [Parameters=[@state='?' (Size = 2)], CommandType='Text', CommandTimeout='30']
      SELECT [o].[Total]
      FROM [Orders] AS [o]
      INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
      WHERE [c].[State] = @state
[489.99,129.50,268.40]

The console logger shows the category name, Microsoft.EntityFrameworkCore.Database.Command[20101], and the endpoint returned [489.99,129.50,268.40], the three Texas totals. My post on logging in ASP.NET Core covers levels, filters and file logging with Serilog.

In a real app, set that category to Information in appsettings.Development.json only, as in my guide to appsettings per environment, and call EnableSensitiveDataLogging() only when builder.Environment.IsDevelopment() is true.

If you’re tuning a data layer, these are worth a look next:

Frequently Asked Questions

Does ToQueryString run the query against the database?

No. It only translates the LINQ to SQL. With logging on, my run showed no Executed DbCommand entry for the ToQueryString() call, only for the queries I actually executed.

Why does the EF Core log show a question mark instead of my parameter value?

EF Core hides parameter values by default because they can be personal data. Add EnableSensitiveDataLogging() in development to log them.

Is it safe to keep EF Core SQL logging on in production?

Logging commands at Information level is safe but noisy, so most apps keep it at Warning and raise it while troubleshooting. Keep sensitive data logging off. See EF Core simple logging on Microsoft Learn for every filter option.

Can I write the generated SQL to a file?

Yes. Pass a StreamWriter‘s WriteLine to LogTo and dispose the writer with the context, or in ASP.NET Core use a logging provider that writes files.

Where can I see the SQL in the Visual Studio debugger?

Hover over the query variable and open its DebugView; the Query entry shows the same SQL as ToQueryString().