In my case for EF 6+, when using this:
System.Data.Entity.Core.Objects.ObjectQuery
As part of this command:
var sql = ((System.Data.Entity.Core.Objects.ObjectQuery)query).ToTraceString();
I got this error:
Cannot cast 'query' (which has an actual type of 'System.Data.Entity.Infrastructure.DbQuery<<>f__AnonymousType3<string,string,string,short,string>>') to 'System.Data.Entity.Core.Objects.ObjectQuery'
So I ended up having to use this:
var sql = ((System.Data.Entity.Infrastructure.DbQuery<<>f__AnonymousType3<string,string,string,short,string>>)query).ToString();
Of course your anonymous type signature might be different.
HTH.