DEV Community

özkan pakdil
özkan pakdil

Posted on

easiest way to print sqls in entity framework

Let say you have DbContext like below

public class Database(DbContextOptions<Database> options) : DbContext(options)
{
    public DbSet<Todo> Todos => Set<Todo>();
}
Enter fullscreen mode Exit fullscreen mode

Just want to print generated SQLs use below class

public class Database(DbContextOptions<Database> options) : DbContext(options)
{
    public DbSet<Todo> Todos => Set<Todo>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder.LogTo(Console.WriteLine);
}
Enter fullscreen mode Exit fullscreen mode

Example generated SQLs for my test app

09/06/2024 15:37:42.815 RelationalEventId.CommandExecuting[20100] (Microsoft.EntityFrameworkCore.Database.Command)
      Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT "t"."Id", "t"."Content", "t"."Done"
      FROM "Todos" AS "t"
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT "t"."Id", "t"."Content", "t"."Done"
      FROM "Todos" AS "t"
info: 09/06/2024 15:37:42.815 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT "t"."Id", "t"."Content", "t"."Done"
      FROM "Todos" AS "t"

Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay