You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Provide a simple way to get SQL statements generated from EF queries #6482
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.
Reacted by Brice Lambson, Drew Noakes, Nemanja Đorđević, Dimko Zhluktenko, ivankarpey, Nikolay, Val, kmolerov, Vyacheslav, Alex Zaytsev and 69 more
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.
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
+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 👍
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?
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);
}
Reacted by Nate, tldzyx, Ṃarc Woolfson, FrancoisM, Boris Valdman, Paul O'Fallon, Sean Lynch, Buddy Favors Jr, Alex Zaytsev, Camilo and 8 more
Reacted by UnderHeavyDevelopment and Thiago Ferreira
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.
.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.
@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).
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.
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);
Activity
JalpeshVadgama commentedon Sep 7, 2016
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
[-]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[/+]JalpeshVadgama commentedon Nov 18, 2016
Since 1.1 is released -https://blogs.msdn.microsoft.com/dotnet/2016/11/16/announcing-entity-framework-core-1-1/ Should we have this available?
JalpeshVadgama commentedon Dec 12, 2016
Guys is there any update when this will be implemented?
ErikEJ commentedon Dec 12, 2016
There is some code available here: #5106 (comment)
simbo1905 commentedon Apr 13, 2017
+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 👍
mguinness commentedon Apr 29, 2017
+1 This was available in EF6 using context.Database.Log.
Ricardo Peres' blogged about getting it using reflection.
d1mnewz commentedon May 10, 2017
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?
manigandham commentedon May 12, 2017
Here's the documentation: https://docs.microsoft.com/en-us/ef/core/miscellaneous/logging
ILoggerFactorywill be automatically injected into yourDbContextconstructor and you can assign it usingoptionsBuilder.UseLoggerFactoryto share the logging config of the rest of your app.If you need something more custom, you can use an implementation of
ILoggerProviderassigned to a newILoggerFactorywhich can then be assigned to theDbContextto log the statements and internal logic.For example: create this logger provider:
Then hook it up in your dbcontext:
JalpeshVadgama commentedon May 12, 2017
Log is a option. But I think it should be something similar to EF6
manigandham commentedon May 12, 2017
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.
110 remaining items
RamType0 commentedon May 26, 2020
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 ?
roji commentedon May 26, 2020
@RamType-0 that's correct (for. NET Framework, I don't know what Unity's plans are).
mguinness commentedon May 26, 2020
https://forum.unity.com/threads/net-5-support.839890/#post-5548063
roji commentedon May 26, 2020
@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).
ocelot-pl commentedon Jun 7, 2020
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.
where
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:
I prefere logging to a file, but of course you can always use:
ErikEJ commentedon Jun 7, 2020
@ocelot-pl is that not for EF 6?