Archive for January 1st, 2009
c# logging linq to sql
by brian on Jan.01, 2009, under .NET, c#, linq, mmsql, sql
I’ve often been frustrated by the sql that linq produces. Usually it’s really good, but occasionally it produced monstrosities. The hard part is getting at the sql that’s produced by a function. Hovering over the statement in the idea is a real pain so instead I created the following class that dumps the sql to a file
public class DCLogger : IDisposable
{
private StringWriter writer;
public DCLogger(System.Data.Linq.DataContext dc)
{
writer = new StringWriter();
dc.Log = writer;
}
#region IDisposable Members
public void Dispose()
{
writer.Flush();
System.IO.File.WriteAllText( "c:\\temp\\sql.log", writer.ToString() );
}
#endregion
}
To use it just create it passing it you data context. The results are written to the file when it’s disposed.
using( DCLogger( dc ) )
{
// ... some linq statement that executes
}
