I found the answer...
So the IQueryable object that I am using for my final query (after defining all of my expressions select and include everything that I need) can be casted to a ObjectQuery.
Once you do that the method ToTraceString() contains all of the SQL generated!
objectQuery.ToTraceString()
If you are building a query and do this earlier(on an earlier variable) it will return the SQL generated up until that point.
Also, the Parameters property contains all of the SQL parameters.
I made a method that I am calling before I return any results for a Linq routine. This method makes the output of the query look pretty for a console application:
private const string debugSeperator =
"-------------------------------------------------------------------------------";
public static IQueryable<T> TraceQuery<T>(IQueryable<T> query)
{
if (query != null)
{
ObjectQuery<T> objectQuery = query as ObjectQuery<T>;
if (objectQuery != null && Boolean.Parse(ConfigurationManager.AppSettings["Debugging"]))
{
StringBuilder queryString = new StringBuilder();
queryString.Append(Environment.NewLine)
.AppendLine(debugSeperator)
.AppendLine("QUERY GENERATED...")
.AppendLine(debugSeperator)
.AppendLine(objectQuery.ToTraceString())
.AppendLine(debugSeperator)
.AppendLine(debugSeperator)
.AppendLine("PARAMETERS...")
.AppendLine(debugSeperator);
foreach (ObjectParameter parameter in objectQuery.Parameters)
{
queryString.Append(String.Format("{0}({1}) \t- {2}", parameter.Name, parameter.ParameterType, parameter.Value)).Append(Environment.NewLine);
}
queryString.AppendLine(debugSeperator).Append(Environment.NewLine);
Console.WriteLine(queryString);
Trace.WriteLine(queryString);
}
}
return query;
}
Note: Debugging needs to be set to true in your config file.
<configuration>
...
<appSettings>
<add key="Debugging" value="true" />
...
</appSettings>
...
<configuration>