Home > Back-end >  How to view raw query which generated by LINQ?
How to view raw query which generated by LINQ?

Time:10-25

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.

CodePudding user response:

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();
  • Related