How do I view the SQL generated by entity framework ?
(In my particular case I\'m using the mysql provider - if it matters)
For me, using EF6 and Visual Studio 2015 I entered query
in the immediate window and it gave me the generated SQL Statement
I am doing integration test, and needed this to debug the generated SQL statement in Entity Framework Core 2.1, so I use DebugLoggerProvider
or ConsoleLoggerProvider
like so:
[Fact]
public async Task MyAwesomeTest
{
//setup log to debug sql queries
var loggerFactory = new LoggerFactory();
loggerFactory.AddProvider(new DebugLoggerProvider());
loggerFactory.AddProvider(new ConsoleLoggerProvider(new ConsoleLoggerSettings()));
var builder = new DbContextOptionsBuilder<DbContext>();
builder
.UseSqlServer("my connection string") //"Server=.;Initial Catalog=TestDb;Integrated Security=True"
.UseLoggerFactory(loggerFactory);
var dbContext = new DbContext(builder.Options);
........
Here is a sample output from Visual Studio console:
This loooong-awaited feature is available in EF Core 5.0! This is from the weekly status updates:
var query = context.Set<Customer>().Where(c => c.City == city); Console.WriteLine(query.ToQueryString())
results in this output when using the SQL Server database provider:
DECLARE p0 nvarchar(4000) = N'London'; SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c] WHERE [c].[City] = @__city_0
Notice that declarations for parameters of the correct type are also included in the output. This allows copy/pasting to SQL Server Management Studio, or similar tools, such that the query can be executed for debugging/analysis.
woohoo!!!
To have the query always handy, without changing code add this to your DbContext and check it on the output window in visual studio.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.Log = (query)=> Debug.Write(query);
}
Similar to @Matt Nibecker answer, but with this you do not have to add it in your current code, every time you need the query.
You can do the following in EF 4.1:
var result = from x in appEntities
where x.id = 32
select x;
System.Diagnostics.Trace.WriteLine(result .ToString());
That will give you the SQL that was generated.
SQL Management Studio => Tools => SQL Server profiler
File => New Trace...
Use the Template => Blank
Event selection => T-SQL
Lefthandside check for: SP.StmtComplete
Column filters can be used to select a specific ApplicationName or DatabaseName
Start that profile running then trigger the query.
Click here for Source information