Search code examples
c#.netsqllinq-to-sqlsql-execution-plan

How to get the execution plan using LINQ to SQL/ADO.NET


Is it possible to get the execution plan of a LINQ to SQL or ADO.NET Query programatically for displaying in debug information? If so, how?


Solution

  • Sure, there are 2 things you will need.

    A custom implementation of DbConnection, DbCommand and DbDataReader. You can use that to intercept all the SQL sent to the DB. You basically set it up so you have a layer that logs all the SQL that is run. (we plan to open source something in this area in the next few months, so stay tuned)

    A way to display an make sense of the data, which happens to be open source here: https://data.stackexchange.com/stackoverflow/s/345/how-unsung-am-i (see the include execution plan option)


    Another approach is to do the diagnostics after the fact by looking at the proc cache. sys.dm_exec_query_stats contains cached plan handles which you can expand.