View SQL generated by Entity Framework version 5

930 Views Asked by At

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.

1

There are 1 best solutions below

0
Anton Kovachev On

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);