Check LINQ Query for SQL Server Database

Is there any way in .NET to find out which LINQ query to the database we are shooting? E.g. I am invoking a query in LINQ, and I want to see that the SQL query is being run to communicate with the database.

Is there any Visual Studio window or some other way?

+6
source share
5 answers

You are looking for something like this

var context = new MyContext(); context.Database.Log = s => Debug.WriteLine(s); 

Then, whenever the request is executed, you will see the output, for example:

 var customers = context.Customers.ToList(); 

Open connection on 30-3-2015 13:48:03 +02: 00

SELECT [Extent1]. [Guid] AS [Guid],
[Extent1]. [FirstName] AS [FirstName],
[Extent1]. [LastName] AS [LastName],
[Extent1]. [Email] AS [Email],
[Extent1]. [Created] AS [Created]
FROM [dbo]. [Customer] AS [Extent1]

- Execution: 30-3-2015 13:48:03 +02: 00

- Completed in 0 ms with the result: SqlDataReader

Closed connection on 30-3-2015 13:48:03 +02: 00

+11
source

If you have a DbContext on which you run your LINQ queries, you can simply set the DbContext.Database.Log property to something like this:

 yourContext.Database.Log = (msg => System.Diagnostics.Debug.Write(msg, "SQL")); 

After that, each SQL query appears in the Debug console from your Visual Studio with the SQL category.

+5
source

You can use SQL Profiler to see how a LINQ expression translates into an SQL statement.

+3
source

You can use the Log property of the DataContext object. In addition, it depends on the type of application used.

For web application: -

 db.Log = Response.Output; 

For console application: -

 db.Log = Console.Out; 

Other than this, you can also use the GetCommand method of the DataContext class. Sql Server Profiler again an obvious option.

+2
source

Source: https://habr.com/ru/post/984433/


All Articles