views:

31

answers:

2

Here's the method i want to write:

public static IEnumerable<String> GetTableNames(this IQueryable<T> query)
{
    //...
}

where the IQueryable is a linq-to-sql query (is there a more specific interface i should use?).

then if i had a query like this

var q = from c in db.Customers
        from p in db.Products
        from cp in db.CustomerProducts
        where c.ID = 3 && cp.CustID == c.ID && p.ID == cp.ProdID
        select new {p.Name, p.Version};
q.GetTableNames();// return ["Customers", "Products", "CustomerProducts"]

basically it would show all the tables that this query touches in the db, it is ok to execute the query to figure this out too (since that is going to happen anyway)? any ideas?

(EDIT: sorry if this is a little too "give me teh codez!", any tips, partial solutions, or explanations of why this is impossible will be considered Thanks! -Luke)

+1  A: 

LINQ-to-SQL allows you to capture the TSQL easily - just set .Log. The problem then is parsing that. I would be tempted to capture the TSQL, and play it back in SSMS with SET STATISTICS IO ON - this gives easily parsed per-table results.

Marc Gravell
wouldn't that cause another roundtrip to the server (in addition to actually running the query)? maybe parsing the TSQL is the way to go...
luke
A: 

You could do DataContext.GetCommand(query).CommandText, then parse that looking for FROM and JOIN clauses (tricky would be cartesian (comma) joins).

David B