Skip to content

Provide a simple way to get SQL statements generated from EF queries #6482

Description

@JalpeshVadgama

Hello Team,

First of all congratulations for this awesome product. We are using it in very extensively. I have one question there. Is there any way to get SQL statement generated in Entity Framework Core. We want to see SQL statements generated and based on that optimize the queries that we are using.

I tried searching it on documentation as well online but have not found anything. Please let me know if there is a way to do this. Right now the only way to profile the database. But in some cases it costs us more when we use Azure SQL databases.

Thank you for anticipation in advance!

Further technical details

EF Core version: 1.0.0
Operating system: Windows 10 Professional
Visual Studio version: Visual Studio 2015

Other details about my project setup: ASP.NET Core, Angular js 1.5 and Entity Framework Core 1.0 with Azure SQL database.

Activity

  1. JalpeshVadgama commented on Sep 7, 2016

    @JalpeshVadgama
    Author

    Logging will not help it is a huge application so there will be lot many things there in logging.Its very hard to find all information there.I want to have something like below.

    http://www.dotnetjalps.com/2012/12/Where-I-can-find-SQL-Generated-by-Entity-framework.html

  2. modified the milestones: 1.1.0, Backlog on Sep 7, 2016
  3. changed the title [-]Is there any way to get SQL Statement generated from the Entity framework core[/-] [+]Provide a simple way to get SQL statements generated from EF queries[/+] on Sep 7, 2016
  4. JalpeshVadgama commented on Dec 12, 2016

    @JalpeshVadgama
    Author

    Guys is there any update when this will be implemented?

  5. ErikEJ commented on Dec 12, 2016

    @ErikEJ
    Contributor

    There is some code available here: #5106 (comment)

  6. simbo1905 commented on Apr 13, 2017

    @simbo1905

    +1 being able to see the generated SQL. Java ORMs typically let you see it at startup else have a build tool option so that you can generate the SQL on the build. there are many good use cases for this such as being able to import it into data migration tooling or to investigate query performance. right now it would be very helpful to see the differences on the official demo app which I am trying to port from SQLServer to Postgres 👍

  7. mguinness commented on Apr 29, 2017

    @mguinness

    +1 This was available in EF6 using context.Database.Log.

    Ricardo Peres' blogged about getting it using reflection.

  8. d1mnewz commented on May 10, 2017

    @d1mnewz

    Also facing this problem, earlier we used Database.Log to investigate performance of EF auto-generated queries, but now we are moving to aspnetcore1.1 and entityframeworkcore.
    Is there already proper way of logging sql queries?

  9. manigandham commented on May 12, 2017

    @manigandham
    Contributor

    Here's the documentation: https://docs.microsoft.com/en-us/ef/core/miscellaneous/logging

    ILoggerFactory will be automatically injected into your DbContext constructor and you can assign it using optionsBuilder.UseLoggerFactory to share the logging config of the rest of your app.

    If you need something more custom, you can use an implementation of ILoggerProvider assigned to a new ILoggerFactory which can then be assigned to the DbContext to log the statements and internal logic.

    For example: create this logger provider:

    using Microsoft.Extensions.Logging;
    using System;
    using System.IO;
    
    namespace EFLogging
    {
        public class MyLoggerProvider : ILoggerProvider
        {
            public ILogger CreateLogger(string categoryName)
            {
                return new MyLogger();
            }
    
            public void Dispose()
            { }
    
            private class MyLogger : ILogger
            {
                public bool IsEnabled(LogLevel logLevel)
                {
                    return true;
                }
    
                public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
                {
                    File.AppendAllText(@"C:\temp\log.txt", formatter(state, exception));
                    Console.WriteLine(formatter(state, exception));
                }
    
                public IDisposable BeginScope<TState>(TState state)
                {
                    return null;
                }
            } 
        }
    }
    

    Then hook it up in your dbcontext:

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var lf = new LoggerFactory();
        lf.AddProvider(new MyLoggerProvider());
        optionsBuilder.UseLoggerFactory(lf);
    }
    
  10. JalpeshVadgama commented on May 12, 2017

    @JalpeshVadgama
    Author

    Log is a option. But I think it should be something similar to EF6

  11. manigandham commented on May 12, 2017

    @manigandham
    Contributor

    What? Logging is all there is, how else would you see the SQL? EF6 and EFCore just have different ways to do the configuration.

    Did you look at the code above? You can use a different logging setup for your db context to so you can see sql statements separately from the rest of your app.

  12. 110 remaining items

  13. added this to the milestone on Mar 13, 2020
  14. RamType0 commented on May 26, 2020

    @RamType0

    EF Core 5.0 requires .NET Standard 2.1,so this feature never become available in .NET Framework 4.8 ,or Unity, isn't it ?

  15. roji commented on May 26, 2020

    @roji
    Member

    @RamType-0 that's correct (for. NET Framework, I don't know what Unity's plans are).

  16. mguinness commented on May 26, 2020

    @mguinness

    https://forum.unity.com/threads/net-5-support.839890/#post-5548063

    .NET 5 is not scheduled for release until November 2020. We would not be doing any work towards supporting it until that release happens and is supported in Mono. So, sometime in 2021 at the earliest.

  17. roji commented on May 26, 2020

    @roji
    Member

    @mguinness note that EF Core 5.0 will support .NET Standard 2.1, not just .NET 5.0. This means that if Unity do support .NET Core 3.1, then it should be possible to use EF Core 5.0 (again, I have no concrete knowledge here).

  18. ocelot-pl commented on Jun 7, 2020

    @ocelot-pl

    Description of the cause of the EF error is often insufficient and you can waste hours searching for the real cause. The following code allows you to write to the log SQL generated during migration to a file. Thanks to its analysis, the problem can be solved in a few minutes.

    internal sealed class Configuration : DbMigrationsConfiguration<MyContext>
    {
        protected override void Seed(MyDatabaseContext context)
        {
    #if DEBUG
            context.Database.Log = s => MyLog.Add(s);
    #endif
            ...
    
            base.Seed(context);
        }
    }
    

    where

    public static class MyLog
    {
        public static void Add(string s) 
        {
             using (StreamWriter sw = File.AppendText(@"c:\temp\sql-log.log")) { sw.WriteLine(s); } 
        }
    }
    

    Thanks to this solution, when starting the database migration in debug mode, we can accurately trace what happened in the database. Thanks to this, within a few minutes I found a solution to the migration problem, which I lost several hours to run.

    An analogous structure can be used in the code, the repository, anywhere, if we want to track SQL:

    using (MyDatabaseContext context = new MyDatabaseContext())
    {
    #if DEBUG
            context.Database.Log = s => MyLog.Add(s);
    #endif
    
            // query the database using EF here.
            ....
    }
    

    I prefere logging to a file, but of course you can always use:

    context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
    
  19. ErikEJ commented on Jun 7, 2020

    @ErikEJ
    Contributor

    @ocelot-pl is that not for EF 6?

  20. modified the milestones: , 5.0.0 on Nov 7, 2020
  21. removed their assignment
    on Sep 1, 2024
  22. added theissue type on Jun 15, 2025
  23. marked EFCore3.1 Sql #19161 as a duplicate of this issue on Jun 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions