Home > Uncategorized > LINQ To SQL – Showing the executed queries that caused the error

LINQ To SQL – Showing the executed queries that caused the error

Ever feel irritated about LINQ to SQL not being able to show you what queries were executed? You never had this issue with normal sql because you were in control of the statement, but with LINQ to SQL you are no longer able to do that!

Fret not just implement the following class in your application, set your datacontext base class to this class (Globals.LoggedDataContext) instead of the default and you are good to go! From now onwards, when you encounter errors during submitchanges, you can see what exactly was executed and find out the problem!


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Globals
{
public class ExecutedSqlTextWriter : System.IO.TextWriter
{
StringBuilder sb = new StringBuilder();
public string ExecutedQueries
{
get { return sb.ToString(); }
}
public void Clear() { sb = new StringBuilder(); }
void WriteToFile(string value)
{
sb.AppendLine(value);
}
public override void Write(char[] buffer, int index, int count)
{
WriteToFile(new String(buffer, index, count));
}

public override void Write(string value)
{
WriteToFile(value);
}

public override Encoding Encoding
{
get { return System.Text.Encoding.Default; }
}
}
public class LoggedDataContext : System.Data.Linq.DataContext
{
public LoggedDataContext(System.Data.IDbConnection connection) : base(connection) { CreateLogWriter(); }
public LoggedDataContext(string fileOrServerOrConnection) : base(fileOrServerOrConnection) { CreateLogWriter(); }
public LoggedDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mapping) : base(connection, mapping) { CreateLogWriter(); }
public LoggedDataContext(string fileOrServerOrConnection, System.Data.Linq.Mapping.MappingSource mapping) : base(fileOrServerOrConnection, mapping) { CreateLogWriter(); }

ExecutedSqlTextWriter theLog { get { return (ExecutedSqlTextWriter)this.Log; } }
void CreateLogWriter()
{
this.Log = new ExecutedSqlTextWriter();
}

public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
{
try
{
base.SubmitChanges(failureMode);
}
catch (Exception ex)
{
string ExecutedSQL = theLog.ExecutedQueries;
throw new ApplicationException(ExecutedSQL, ex);
}
theLog.Clear();
}
}
}

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: