How to log with Linq to Sql?<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to log with Linq to Sql?

Posted on: August 27, 2011

It's possible to log all SQL queries generated by Linq to Sql with C# code. This can be useful when debugging or to optimize how the Linq is done.

1DataClasses1DataContext db = new DataClasses1DataContext();
2 StringWriter sw = new StringWriter();
3 db.Log = sw;
4
5this.gridLinqToSql.DataSource = db.Customers.Where(c => c.CustomerID.StartsWith("A"));
6this.gridLinqToSql.DataBind(); //Here is when the Linq query will be executed.
7
8sqlLinqToSql.Text = sw.GetStringBuilder().ToString(); // Here is the output of the SQL commands

Linq to Sql use a DataContext object that is generated with the .dbml file.

For example, in this test project, the .dbml file name is DataClasses1.dbml.

From there, this object contain a Log property that takes a TextWriter.

The TextWriter class comes from the System.IO namespace and it's an abstract class.

The namespace contain two concrete classes that inherit from this class.

The first one is StringWriter that has been used in the example above. This class has a StringBuilder and when using the property GetStringBuilder() of the StringWriter let you get a reference on it. From there, using the ToString() method give a String with all the SQL used to get the information.

The result looks like this:

1SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle]
2 FROM [dbo].[Customers] AS [t0]
3 WHERE [t0].[CustomerID] LIKE @p0
4
5-- @p0: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [A%]
6-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 4.0.30319.1

The Log return the SQL statement (or many SQL statement if many calls has been done) with a parameter way (@p...). After the SQL Statement, each parameter details is written. For example, you can find the type and the size of a SQL parameter.

To conclude, using the Log property is interesting to get the SQL detail without using a SQL Profiler.

Of course, a good practice would be to not log all the queries in production environment.