views:

22

answers:

2

I have ADO.NET EF expression like:

db.Table1.Select(
  x => new { ..., count = db.Table2.Count(y => y.ForeignKey.ID == x.ID) })

Does I understand correctly it's translated into several SQL client-server requests and may be refactored for better performance?

Thank you in advance!

+2  A: 

Yes - the expression will get translated (in the best way it can) to a SQL query.

And just like any T-SQL query, an EF (or L2SQL) query expression can be refactored for performance.

Why not run SQL profiler in the background to see what it is getting executed, and try and optimize the raw T-SQL first - which will help optimize the expression.

Or if you have LinqPad, just optimize the T-SQL query and get LinqPad to write your query for you.

Also, im not really sure why you have specified the delegate for the Count() expression.

You can simply do this:

var query= from c in db.Table1
                  select new { c.CustomerID, OrderCount = c.Table2s.Count() };
RPM1984
I have Sql Express and was too lazy to install some 3d party profiler. But after your comment I'll take a closer look under profiler
Andrew Florko
You're not going to be able to write effective LINQ-EF/LINQ-SQL queryies until you see whats happening behind the scenes (ie against SS). At the very least, pop your query into LinqPad and see what is being executed.
RPM1984
Thank you for the LinqPad - it's amazing. I checked both linq queries (with inner db instance and grouping) -> they both executed in one request
Andrew Florko
+1  A: 

The answer is NO - this query will be translated into one client-to-RDBMS request.

RPM1984 advised to use LinqPad. LinqPad showed that the query will be translated into very straightforward SQL expression. Approach with grouping will be translated into another SQL expression but still will be executed in one request.

Andrew Florko
I misunderstood your question, which was my mistake. Understand LINQ is all about expressions, only when you fire off the enumerator will the query be executed (.SingleOrDefault, .ToList, .Count) etc. Because you are only doing one of these once, it will fire 1 query.
RPM1984