10

I'm trying to view the generated sql that Entity Framework 5.0 generates from an entities query. All over the web, everyone says to cast the IQuerable object to an ObjectQuery object and then use the toTraceString() method to return the generated query.

However I keep getting an invalid case exception:

    Unhandled Exception: System.InvalidCastException: Unable to cast object of type
'System.Data.Entity.Infrastructure.DbQuery`1[System.String]' to type 'System.Data.Objects.ObjectQuery'.

What is the new way to do this in Entity Framework 5?

Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
Rafi
  • 2,433
  • 1
  • 25
  • 33

2 Answers2

15

You can view the generated SQL from an IQueryable using .ToString(), e.g.

var query = context.People.Where(x => x.DomainId == 1);
Console.WriteLine(query.ToString());
Richard
  • 29,854
  • 11
  • 77
  • 120
  • 1
    Wow! That was easy. Thanks. I figured toString() with return the object type like it normally does. – Rafi Apr 14 '13 at 19:19
2

Are you using SQL Server? If so, try using the profiler. Tools->SQL Server Profiler in the development version of Management Studio

Kirsten
  • 15,730
  • 41
  • 179
  • 318