Attaching a TextWriter to a LINQ DataContext
Sometimes we need to log the commands and results of querying the database using LINQ. This could be for performance tuning reasons, general logging practices, or some other reason. Microsoft has made it easy for us to attach a TextWriter object to the LINQ DataContext, which will log all commands and results issued on the DataContext.
In the example below, we have a LINQ DataContext (LinqDBDataContext) object to which we will attach a TextWriter. The TextWriter will output it's information to a local text file. Notice in our example, we are using a StreamWriter, which inherits from TextWriter. Any object which inherits from TextWriter can be used.
Attaching a TextWriter to a LINQ DataContext
// create our streamwriter and wrap it in a using statement
// so it will be properly disposed when we are done with it
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"c:tempdatacontext.log"))
{
// create our datacontext and wrap it in a using statement, also
using (LinqDBDataContext linqDB = new LinqDBDataContext())
{
// attach the streamwriter to the DataContext
linqDB.Log = sw;// call a stored procedure or other SQL query
// SQL commands and results will be written to sw
// …..
}
}
As you can see in the example above, to attach a TextWriter (or other TextWriter inherited object) to the DataContext, you assign it to the Log property.
Visit the LINQ Exchange Forum to post your comments, questions, or suggestions.
loading...
loading...
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.
