giovedì, maggio 19, 2011

How to intercept the sql query generated by an EntityDataSource

The EntityDataSource (= Entity Framework data source) hides SQL details. But sometimes you could need to see the auto generated SQL command.

Simple: intercept the QueryCreated event of the EntityDataSource

protected void EntityDataSource1_QueryCreated(object sender, QueryCreatedEventArgs e)
   LabelX.Text = (e.Query as System.Data.Objects.ObjectQuery).ToTraceString();

If are using an ObjectContext, you can extract the SQL casting the query to ObjectQuery.

var db = .... ObjectContext...
var query = (from x in TableName select x);
string sqlquery = (query as System.Data.Objects.ObjectQuery).ToTraceString();