using (testEntities MyEntity = new testEntities()) { #region linq to entities 内容练习3 var result = from s in MyEntity.stuinfo where s.username == "pkm" select new { username=s.username, age=s.age }; var psql = result.GetType().GetMethod("ToTraceString").Invoke(result, null);//得到原始sql语句 Console.WriteLine(psql); #endregion }
以下函数可以得到相同的结果:
/// <summary> /// 输入生成的SQL语句 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="query">查询结果的变量</param> /// <returns></returns> private static string GetSQL<T>(IQueryable<T> query) { return query.GetType().GetMethod("ToTraceString").Invoke(query,null).ToString(); } //请用方法 Console.WriteLine(GetSQL(result));