views:

37

answers:

5

Morning all.

Just a quick one for you - where can I find the SQL that is executed when a LINQ statement fires?

I have the following code that works a treat,

 var r = (from p in getproductweightsbuyer.tblWeights
                     where p.MemberId == memberid &&
                              p.LocationId == locationid
                     select p);

            if (buyer != "Not Specified")
                r = r.Where(p => p.UnitUserField1 == buyer);

            if (subcategory != "Not Specified")
                r = r.Where(p => p.UnitUserField2 == subcategory);

I'm just not sure of the SQL that is firing in the conditional where clause.

+1  A: 

if you debug your code you can put a breakpoint and analyze the value of r, which will have the actual SQL code in it.

Stefanvds
Thanks Stefan - I couldn't remember at which point the SQL would be exposed.
Ricardo Deano
+2  A: 

If you have the database context at hand you could try:

context.GetCommand(query).CommandText
Thorsten Dittmar
Nice - I did not know about this. Thanks Thorsten.
Ricardo Deano
+1  A: 

As well as the above options, you can also run up SQL profiler and see the actual SQL sent down the wire to the DB.

Paddy
That'd make sense...you can tell it is Monday!!! Cheers Paddy.
Ricardo Deano
+1  A: 

If you use LINQ to SQL you can set the DataContext.Log property. This will log the SQL when you execute the query:

getproductweightsbuyer.Log = Console.Out;

var r = (from p in getproductweightsbuyer.tblWeights
                    where p.MemberId == memberid &&
                             p.LocationId == locationid
                    select p);

           if (buyer != "Not Specified")
               r = r.Where(p => p.UnitUserField1 == buyer);

           if (subcategory != "Not Specified")
               r = r.Where(p => p.UnitUserField2 == subcategory);

foreach (var row in r)
  ...
Martin Liversage
A: 

When you're using LINQ to SQL, you can hook a TextWriter to the DataContext.Log property:

context.Log = Console.Out;

However, writing to the console isn't that useful when running inside of Visual Studio, so you might try this solution.

Steven