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'sIQueryable /ObjectQuery Use ToTraceString instead. If it's an IDbSet or DbSet, utilize that.ToString directly.

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

Popular Answer

I was unable to obtain using EF 6. ToString() will produce SQL for a query like:

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

When I did, I realized how to record it to debug output using:

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

Set the above value just before loading queries (duh):

Here, db is an instance of a class that is descended from DbContext.



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