Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to analyse LINQ queries

Tags:

asp.net

linq

I swear I've seen how to do this before, but now that I actually need to do it I can't remember where I saw it at. I need two different things --

1) to see the actual SQL query that is generated by a LINQ query and 2) when the SQL query actually hits the database to do whatever (CRUD operations)

Is there a tool that will allow me to do this?

EDIT:

Sorry, should have given more detail. -- LINQ to Entities is what I'm using. -- Also, I don't have admin rights on our instance of SQL Server, so I can't use SQL Profiler. I could always call the DBA and have them do it for me, but it's a hassle. I should have mentioned that and I apologize. What I really want is a tool that I can use on my own box that will allow me to see when a LINQ query hits the database while I am in debug mode (debugging and stepping through the code).

like image 224
Jagd Avatar asked Dec 12 '22 14:12

Jagd


2 Answers

Try using SQL Profiler. It's great for seeing what LINQ to SQL is generating.

SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft® SQL Server™. You can capture and save data about each event to a file or SQL Server table to analyze later. For example, you can monitor a production environment to see which stored procedures are hampering performance by executing too slowly.

LINQPad is also a great tool for writing linq and sql statements for testing.

LINQPad compiles your queries using .NET's CSharpCodeProvider (or VBCodeProvider). Because C# and VB are statically typed, any database objects that you reference need the backing of a typed DataContext. For performance, LINQPad builds typed DataContexts on the fly using Reflection.Emit rather than generating and compiling source code. It uses LINQ to SQL rather than Entity Framework because LINQ to SQL is an order of magnitude faster in building the metamodel when instantiated.

like image 180
hunter Avatar answered Dec 22 '22 01:12

hunter


The .ToString() on the IQueryable for LINQ to SQL will show you the query.

var myquery = from x in dbcontext.MyTable
              where x.Prop1 == someValue
              select new {
                  value1 = x.prop1,
                  value2 = 5,
              };

var sqlstring = myquery.ToString(); //<= look in this string
like image 42
Matthew Whited Avatar answered Dec 22 '22 01:12

Matthew Whited