views:

194

answers:

2

I'm interested in tracing database calls made by LINQ to SQL back to the .NET code that generated the call. For instance, a DBA might have a concern that a particular cached execution plan is doing poorly. If for example a DBA were to tell a developer to address the following code...

exec sp_executesql N'SELECT [t0].[CustomerID]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[ContactName] LIKE @p0
ORDER BY [t0].[CompanyName]',
'N'@p0 nvarchar(2)',@p0=N'c%'

...it's not immediately obvious which LINQ statement produced the call. Sure you could search through the "Customers" class in the auto-generated data context, but that'd just be a start. With a large application this could quickly become unmanageable.

Is there a way to attach an ID or label to SQL code generated and executed by LINQ to SQL? Thinking out loud, here's an extension function called "TagWith" that illustrates conceptually what I'm interested in doing.

var customers = from c in context.Customers
                where c.CompanyName.StartsWith("c")
             orderby c.CompanyName
             select c.CustomerID;

foreach (var CustomerID in customers.TagWith("CustomerList4"))
{
    Console.WriteLine(CustomerID);
}

If the "CustomerList4" ID/label ends up in the automatically-generated SQL, I'd be set. Thanks.

+1  A: 

Have you looked at capturing the T-SQL with the DataContext.Log property? If you were able to capure it into an object that also had your tag property you might be able to catalog the SQL your application executes.

MotoWilliams
A: 

There is no public way to modify the underlying SQL that LINQ to SQL generates to implement such a tagging facility. You could implement the Log property in such a way it writes out a text log file with some call stack information to show which methods generated which SQL statements for reference.

DamienG