4

eg.

var result = myObject.Where(x => x.prop == 5);

string s = result.toSQL();

Result:

s is "SELECT * FROM [myObjects] WHERE prop = 5"

NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • Take a look at http://stackoverflow.com/questions/3980874/get-tracestring-for-your-business-objects-in-the-entity-framework – Eranga Jul 05 '12 at 11:07

2 Answers2

8

If it's IQueryable/ObjectQuery you can use ToTraceString. If it's IDbSet/DbSet you can use ToString directly.

cincura.net
  • 4,130
  • 16
  • 40
0

Using EF 6 I could not get .ToString() to return SQL for something similar to:

   db.Entry(parent)
   .Collection(p => p.Children)
   .Query()
   .Where(c => c.Active)
   .Load();

Then I remembered you can log it to debug output with:

db.Database.Log = (entry) => System.Diagnostics.Debug.WriteLine(entry);

Just set above before loading queries (duh) :)

db here is an instance of some DbContext derived class.

Quinton Smith
  • 2,550
  • 18
  • 17