It is very common that may come in your mind that, how we can see SQL query being generated at the back end for LINQ query.

Assume you have a LINQ as below,

image

If you want to view SQL query generated for above LINQ on console screen you need to add just one line of code as below,

image

If you closely examine log it is a property in DataContext class and it is of type textwriter.

image

Since it is of type text writer you can save it to a text file as well. If you want to log you need to follow below steps.

Step1

Create a class overriding System.IO.TextWriter class.

image

Step 2

Configure log file in configuration

image

Step 3

Log the query as below

image

Full source code of above explanation is given below ,

01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05 using System.IO;
06  
07 namespace Relatedtable
08 {
09     class Program
10     {
11  
12         static DataClasses1DataContext context;
13         static void Main(string[] args)
14         {
15             context = new DataClasses1DataContext();
16             context.Log = Console.Out;
17             context.Persons.InsertOnSubmit(
18                             new Person
19                             {
20                                 FirstName = "The ",
21                                 LastName = "Poet",
22                                 HireDate = DateTime.Now,
23                                 OfficeAssignment = new OfficeAssignment
24                                 {
25                                     Location = "Jamshedpur"
26                                 }
27  
28                             }
29                             );
30             context.Log = new LogLINQSQL();
31             context.SubmitChanges();
32             context.Log = Console.Out;
33             Console.ReadKey(true);
34  
35 var result = from r in context.Persons
36                          where r.FirstName=="Dhananjay"
37                          select r ;
38             context.Log = Console.Out;
39             foreach (var r in result)
40             {
41                 Console.WriteLine(r.FirstName);
42             }
43             Console.ReadKey(true);
44  
45   }
46  
47  }
48  
49     class LogLINQSQL : System.IO.TextWriter
50     {
51         public override void Write(char[] buffer, int index, int count)
52         {
53             System.Diagnostics.Debug.Write(new String(buffer, index, count));
54         }
55  
56         public override void Write(string value)
57         {
58             System.Diagnostics.Debug.Write(value);
59         }
60  
61         public override Encoding Encoding
62         {
63             get return System.Text.Encoding.UTF8; }
64         }
65     }
66 }

I hope this post was useful. Thanks for reading  Smile