How do I view the SQL generated by entity framework ?
(In my particular case I\'m using the mysql provider - if it matters)
Most of the answers here were EF6-specific. Here's one for those of you still using EF4.
This method replaces the @p__linq__0/etc. parameters with their actual values, so you can just copy and paste the output into SSMS and run it or debug it.
///
/// Temporary debug function that spits out the actual SQL query LINQ is generating (with parameters)
///
/// IQueryable object
private string Debug_GetSQLFromIQueryable(IQueryable q)
{
System.Data.Objects.ObjectQuery oq = (System.Data.Objects.ObjectQuery)q;
var result = oq.ToTraceString();
List paramNames = new List();
List paramVals = new List();
foreach (var parameter in oq.Parameters)
{
paramNames.Add(parameter.Name);
paramVals.Add(parameter.Value == null ? "NULL" : ("'" + parameter.Value.ToString() + "'"));
}
//replace params in reverse order, otherwise @p__linq__1 incorrectly replaces @p__linq__10 for instance
for (var i = paramNames.Count - 1; i >= 0; i--)
{
result = result.Replace("@" + paramNames[i], paramVals[i]);
}
return result;
}