Tag: Display SQL Queries In Entity Framework Core

  • Display SQL Queries In Entity Framework Core

    Display SQL Queries In Entity Framework Core

    Entity Framework Core in .NET is highly effective at automatically generating and executing queries behind the scenes. However, there may be instances where it is beneficial to view the auto-generated queries. This could be for purposes such as verifying the accuracy of the query or troubleshooting performance-related issues.

    To achieve this, you can easily enable the display of the auto-generated SQL queries on the application console.

    To configure console logging, you should include the OnConfiguring method within the database context class as shown below.

    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions options)
            : base(options)
        {
        }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
           => optionsBuilder.LogTo(Console.WriteLine);
    }
    


    Important: This code should be used for development and debugging purposes only. It should never be used in a production environment.

    Hope this was helpful. Feel free to give feedback in the comments. Thank you!