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

Top comments (0)