'View SQL generated by Entity Framework version 5 [duplicate]

How can I view the complete sql query generated by Entity Framework (version 5)? I can view it using

query.ToString()

but I don't get all the parameters with it. I get a lot of variables like @p_linq_0.



Solution 1:[1]

You can log the SQL queries in your Console Output window by using EnableSensitiveDataLogging EnableSensitiveDataLogging also log more details when an exception occurs in EF

 public ApplicationDbContext CreateContext()
        => new ApplicationDbContext(
            new DbContextOptionsBuilder<ApplicationDbContext>()
                .UseSqlServer(Configuration["TestDBConnection"])
                .EnableSensitiveDataLogging()
                .Options);

From EF Core 5.0 onwards you can also use the LogTo method which takes an Action delegate as a parameter and enables you to log into the Console or to a file, or to a NoSQL database for example

     public ApplicationDbContext CreateContext()
        => new ApplicationDbContext(
            new DbContextOptionsBuilder<ApplicationDbContext>()
                .UseSqlServer(Configuration["TestDBConnection"])
                .LogTo(Console.WriteLine)
                .Options);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anton Kovachev