Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 3 - How to view LINQ to SQL generated SQL queries

Suggested Videos
Part 1 - LINQ to SQL
Part 2 - Insert Update Delete using LINQ to SQL



In this video we will discuss, how to view the SQL statements generated by LINQ to SQL. For debugging, it is necessary to view the generated SQL statements. There are several ways to do this.



Using the Log property of the DataContext object
using (SampleDataContext dbContext = new SampleDataContext())
{
    // Write the generated sql query to the webform
    dbContext.Log = Response.Output;

    // Write the generated sql query to the Console window
    // dbContext.Log = Console.Out;

    var linqQuery = from employee in dbContext.Employees
                    select employee;

    GridView1.DataSource = linqQuery;
    GridView1.DataBind();
}

Using ToString() method
using (SampleDataContext dbContext = new SampleDataContext())
{
    var linqQuery = from employee in dbContext.Employees
                    select employee;

    string sqlQuery = linqQuery.ToString();
    Response.Write(sqlQuery);

    GridView1.DataSource = linqQuery;
    GridView1.DataBind();
}

Using GetCommand() method of DataContext object
using (SampleDataContext dbContext = new SampleDataContext())
{
    var linqQuery = from employee in dbContext.Employees
                    select employee;

    Response.Write(dbContext.GetCommand(linqQuery).CommandText);
    Response.Write("<br/>");
    Response.Write(dbContext.GetCommand(linqQuery).CommandType);

    GridView1.DataSource = linqQuery;
    GridView1.DataBind();
}

Finally, we can also use SQL profiler.

LINQ to SQL Tutorial

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.