Polaris Nation
Polaris Nation

Reputation: 1225

How to view raw query which generated by LINQ?

I want to see the generated sql to debug with Console.WriteLine(); In Visual studio Code, with Console.WriteLine(), I can't see the raw query;

    var result = from employee in db.EmployeeUsers
                        ...
             select employee.id..;
     string sql = result.ToString();

 Console.WriteLine(sql);

But it show like this

Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[<>f__AnonymousType1641]

How I can see raw query like this?

[SELECT employee.id FROM ... WHERE...;]

I set this first,

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
     ,"Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  },

But I didn't see if I set it up wrong. And then I set

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder.LogTo(Console.WriteLine);

But it shows every Raw Query.

I simply want Query to be printed only on the part I designated in Visual Studio Code Terminal.

Upvotes: 0

Views: 2001

Answers (1)

DasKr&#252;melmonster
DasKr&#252;melmonster

Reputation: 6060

Apparently you can call .ToQueryString() or use the Query property.

https://stackoverflow.com/a/68797954/1974021

var result = from employee in db.EmployeeUsers
                    ...
         select employee.id..;
string sql = result.ToQueryString();

Upvotes: 2

Related Questions