问题
eg.
var result = myObject.Where(x => x.prop == 5);
string s = result.toSQL();
Result:
s
is "SELECT * FROM [myObjects] WHERE prop = 5"
回答1:
If it's IQueryable
/ObjectQuery
you can use ToTraceString. If it's IDbSet/DbSet you can use ToString
directly.
回答2:
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.
来源:https://stackoverflow.com/questions/11342669/in-linq-to-entities-can-you-convert-an-iqueryable-into-a-string-of-sql