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

雨燕双飞 提交于 2019-12-23 18:01:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!