How to Detect Select n+1 problems in Linq to SQL?

2019-02-18 13:43发布

问题:

What is the best way to detect Select n+1 problems if i am using linq to SQL, right now we are working on a project and it seem to be pretty slow to display some lists. What is the best method to detect this?

回答1:

Maybe this will help:

http://ayende.com/Blog/archive/2009/11/13/linq-to-sql-profiler-is-now-on-public-beta.aspx http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx http://visualstudiogallery.msdn.microsoft.com/ru-ru/d5a64d5a-174a-4357-ad84-dbeeec030f23

Or you can use SQL Profiler and just check if queries are executed when you access individual list items.



回答2:

This won't outright detect n+1 problems, but they're pretty easy to spot when you look at your generated SQL.

The DataContext.Log property takes a TextWriter that will output the generated SQL and some other diagnostic information. Here's an implementation that logs to the output. Linq to SQL DebuggerWriter. Here's the simple example of how to use the DebuggerWriter.

DataContext db = new DataContext();
#if DEBUG
db.Log = new DebuggerWriter();
#endif