In Linq to Entities can you convert an IQueryable into a string of SQL?

entity-framework linq-to-entities

Question

eg.

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

string s = result.toSQL();

Result:

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

1
3
7/5/2012 10:41:55 AM

Accepted Answer

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

8
7/5/2012 11:36:02 AM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow