ObjectContext
先定义一个扩展方法:
public static string ToTraceString<T>(this IQueryable<T> t) { string sql = ""; ObjectQuery<T> oqt = t as ObjectQuery<T>; if (oqt != null) sql = oqt.ToTraceString(); return sql; }
使用方法:
var query = db.Call.Where(a => a.CustomerId == id && a.IsActive == "Y"); //不能ToList(),必须为IQueryble<T>类型
var sql= query.ToTraceString();
DataContext:
定义一个输出到debug窗口的类:
public class DebugTextWriter : System.IO.TextWriter { public override void Write(char[] buffer, int index, int count) { System.Diagnostics.Debug.Write(new String(buffer, index, count)); } public override void Write(string value) { System.Diagnostics.Debug.Write(value); } public override Encoding Encoding { get { return System.Text.Encoding.Default; } } }
使用:
using (var db = new NorthwindDataContext()) { List<Call> calls = (from p in db.Call where p.CustomerId == "12414" orderby p.UpdateTime select p).ToList(); //必须Tolist查询,延迟加载无法获得sql语句 db.Log=new DebugTextWriter(); }
注:DataContext也可以使用下列ToString()方法。
DBContext 最简单,只需要ToString()方法。
var query = db.Call.Where(a => a.CustomerId == id && a.IsActive == "Y"); //不能ToList(),必须为IQueryble<T>类型
var sql = query.ToString();