Saturday, October 24, 2009

Output your SQL when using Linq in ASP.NET

image

I used both Linq Data Source and straight Linq.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
StringWriter sw = new StringWriter();
protected void Page_Load()
{
// Using Linq Data Source
LinqDataSource1.ContextCreated += (sender, e) =>
{
sw.WriteLine("Grid 1 SQL");
((DataClassesDataContext)e.Result).Log = sw;
};

// Using Linq
DataClassesDataContext db = new DataClassesDataContext();

var results = from c in db.Customers
where c.City == "London"
select c;

GridView2.DataSource = results;

sw.WriteLine("Grid 2 SQL");
db.Log = sw;
GridView2.DataBind();

}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
writer.Write("<hr><p>LINQ to SQL Trace Console</p><p><textarea cols='100' rows='15' readonly='true'>");
writer.Write(sw.ToString());
writer.Write("</textarea></p>");
}

}

0 comments:

Post a Comment