How to: Display Generated SQL (LINQ to SQL)

You can view the SQL code generated for queries and change processing by using the Log property. This approach can be useful for understanding LINQ to SQL functionality and for debugging specific problems.

Example

The following example uses the Log property to display SQL code in the console window before the code is executed. You can use this property with query, insert, update, and delete commands.

The lines from the console window are what you would see when you execute the Visual Basic or C# code that follows.

SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactT

itle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Coun

try], [t0].[Phone], [t0].[Fax]

FROM [dbo].[Customers] AS [t0]

WHERE [t0].[City] = @p0

-- @p0: Input String (Size = 6; Prec = 0; Scale = 0) [London]

-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.20810.0

AROUT

BSBEV

CONSH

EASTC

NORTS

SEVES

db.Log = Console.Out
Dim custQuery = _
    From cust In db.Customers _
    Where cust.City = "London" _
    Select cust

For Each custObj In custQuery
    Console.WriteLine(custObj.CustomerID)
Next
db.Log = Console.Out;
IQueryable<Customer> custQuery =
    from cust in db.Customers
    where cust.City == "London" 
    select cust;

foreach(Customer custObj in custQuery)
{
    Console.WriteLine(custObj.CustomerID);
}

See Also

Other Resources

Debugging Support (LINQ to SQL)