views:

43

answers:

3

I have something like this in a repository:

var results = db.EventSet.Include("Events")
                               .Include("TestResults")
                               .Include("Events.Donors")
                               .Include("Events.DonorPanels")
                               .Include("Events.Locations")
                               .Include("Events.DonorPanels.AgenciesDonors")
                               .Where(x => x.Events.Donors.DonorId == DonorId 
                                      && x.Events.Active)
                               .OrderByDescending(x => x.Events.ScheduledDate)
                               .ThenByDescending(x => x.CreatedAt)
                               .ToList();

How can I see the SQL generated by EF for this?

+1  A: 

One easy way is to use the SQL Server Profiler, but get ready for a nasty surprise.

Mark Seemann
In the Profiler, Duration (start/stop) is ~25,000 (wall clock is around 4 seconds). Yet the same query dumped as straight SQL into the engine via SM executes sub-second. Is EF result processing overhead really this inefficient? What else could be causing the difference between a raw query being relatively fast and the C# MVC/EF method taking donkey years?
dale
Dale, query compilation (LINQ -> ADO CCT) takes some time, too. Workaround is `CompiledQuery`. But your includes may result in a huge amount of unneeded fields, and mapping that does take some time. Use projections instead of including the world + its dog to fix that.
Craig Stuntz
+2  A: 

SQL Profiler.

Alternately, change your code to:

var q = db.EventSet.Include("Events")
                           .Include("TestResults")
                           .Include("Events.Donors")
                           .Include("Events.DonorPanels")
                           .Include("Events.Locations")
                           .Include("Events.DonorPanels.AgenciesDonors")
                           .Where(x => x.Events.Donors.DonorId == DonorId 
                                  && x.Events.Active)
                           .OrderByDescending(x => x.Events.ScheduledDate)
                           .ThenByDescending(x => x.CreatedAt);
var sql = (q as ObjectQuery).ToTraceString();
var results = q.ToList();
Craig Stuntz
A: 

Profiler is definitely a great way to go, but if you're developing against SQL Server express, it's not available (that I'm aware of).

Another option would be to use LINQPad. It will show you the SQL, Lambda, IL, and results generated for linq queries. Definitely a must-have tool if you're doing EF development IMO.

http://www.linqpad.net/

jkody21