I need a way to traverse a LINQ-to-SQL expression tree to extract the table name(s) in the query. Even just the first table used in the query would probably be sufficient.
Example:
var query = from c in Db.Customers select c;
And the ideal function:
string TableName = ExtractTablesFromQuery(query);
Would return string “Customers”
LINQ to SQL doesn’t expose this functionality for you so you have two options.
Use the dataContext.GetCommand(myQuery) function and parse the TSQL
This can get a little tricky with joins etc. but will guarantee you get the exact table names that are going to be involved.
Visit the expression tree yourself
This isn’t too difficult but has the problem in that LINQ to SQL infers and optimizes which tables to actually use so you won’t get a 100% accurate result of what will happen. e.g. if you joined a table but didn’t return any of the results it would get optimized out but you wouldn’t know this by visiting the expression tree unless you optimized exactly like LINQ to SQL does (which would be a lot of work).
If you want to try #2 anyway here’s an example to get you started:
To use this you would foreach over the results from dataContext.GetTables(myQuery);