DataContext.Log - Logging LINQ To SQL Output to Console or Debugger Output Window

DataContext.Log - Logging LINQ To SQL Output to Console or Debugger Output Window

by David Hayden ( Microsoft MVP C# ), Filed: LINQ To SQL, O/R Mappers

 

Another quick tutorial on LINQ To SQL to append to the rest:

 

Although you can always use SQL Server Profiler to view the SQL generated by LINQ To SQL, there is a DataContext.Log Property that you can assign a TextWriter to view the SQL generated.

For playing in a console application, you have the option of assigning Console.Out, which will display the SQL output to the console:

 

using (NorthwindDataContext context =
new NorthwindDataContext()) { context.Log = Console.Out; Customer customer = context.Customers.Single<Customer> (c => c.CustomerID.Equals("ALFKI")); }

 

However, displaying the SQL code in the debugger output window for non-console applications and even console applications is better using something like DebuggerWriter, which is a wrapper around System.Diagnostics.Debugger:

 

using (NorthwindDataContext context =
new NorthwindDataContext()) { context.Log = new DebuggerWriter(); Customer customer = context.Customers.Single<Customer> (c => c.CustomerID.Equals("ALFKI")); }

 

You can write your own DebuggerWriter, or you could check out the code from Kris Vandermotten:

Sending the LINQ To SQL log to the debugger output window

Very cool, Kris!

 

News Feed: David Hayden ( Microsoft MVP C# )

Filed: LINQ To SQL, O/R Mappers

posted on Friday, August 17, 2007 1:57 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices