2

I grab the SQL that will be issued by a LINQ to SQL command and store it in a string in my C# code. I do not want to have it sent to console out, not do I want to analyze it separately in SQL Studio or LinqPad. I want to have that string so that my program can do what it wants with the string. (In reality, I will send it to log4net, but that's incidental).

Does anyone know how to get this? I know that the SQL is not actually issued to the database until you start walking through the iterators, but I am hoping that perhaps there is a way to get the SQL beforehand.

Wouter de Kort
  • 39,090
  • 12
  • 84
  • 103
Daniel Williams
  • 8,912
  • 15
  • 68
  • 107

2 Answers2

6

If you are using the Entity Framework you can use the ToTraceString() method on an ObjectQuery like this:

ObjectQuery<Product> productQuery =
  from p in context.Products
  select p;

string sql = productQuery.ToTraceString();

If you are using Linq to Sql, you're DataContext has a Log property that you can use to get the Sql output.

    StringBuilder logBuilder = new StringBuilder();
    db.Log = new StringWriter(logBuilder);
    var custQuery =
        (from cust in db.Customers
        where cust.City == "London"
        select cust).ToList();

   string sql = logBuilder.ToString();
Wouter de Kort
  • 39,090
  • 12
  • 84
  • 103
2

You don't say if you are using Linq to SQL or EF, but with L2S, the database context object has a Log property that can be used for this purpose. You can learn more about this property here. Keep in mind you won't be able to execute the generated SQL without some modifications.

Hosea146
  • 7,412
  • 21
  • 60
  • 81