Asp.Net EF查看生成sql(MiniProfiler)
查看ef生成的sql有很多种方法,这里介绍两种几种的方法
方法1:浏览器直接方法/Home/getsql直接查看sql
//方法1:浏览器直接方法/Home/getsql直接查看sql public string GetSql() { dbEntities db = new dbEntities(); return db.news.Where(m => m.hot == 1).OrderByDescending(m => m.ID).Take(5).ToString(); }
方法2:把生成的sql保存在磁盘中
//方法2:把sql保存在磁盘中 public ActionResult Index2() { dbEntities db = new dbEntities(); var sw = new StreamWriter(@"d:\" + DateTime.Now.ToFileTime().ToString() + ".log") { AutoFlush = true }; db.Database.Log = s =>{sw.Write(s);}; var list = db.news.Where(m => m.hot == 1).OrderByDescending(m => m.ID).Take(5).ToList(); return View(list); }
方法3:MiniProfiler
建议使用vs2015以上nuget搜索MiniProfiler安装
需要安装MiniProfiler、MiniProfiler ef6、MiniProfiler mvc,如果最新版安装不成功的话安装低版本即可
安装完成后需要设置Global.asax、web.config、view
Global.asax(新加红色代码)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using StackExchange.Profiling; using StackExchange.Profiling.EntityFramework6; namespace cms.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); BundleTable.EnableOptimizations = true;//js/css压缩 MiniProfilerEF6.Initialize();//MiniProfiler监控ef } protected void Application_BeginRequest() { if (Request.IsLocal)//这里是允许本地访问启动监控,可不写 { MiniProfiler.Start(); } } protected void Application_EndRequest() { MiniProfiler.Stop(); } } }
web.config
<system.webServer> <validation validateIntegratedModeConfiguration="false" /> <handlers> <add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" /> </handlers> </system.webServer>
随便一个view
@using StackExchange.Profiling;
@MiniProfiler.RenderIncludes();
注意:如果想监控所有的页面,推荐加在布局页(_Layout)中
运行效果
//成功一定有方法,失败一定有原因。