针对于.Net MVC+EF的开发模式,MiniProfilter提供了监控调试EF的功能,可以查看运行了那些sql,sql执行的时间等。
一、安装
vs打开NuGet的管理NuGet程序包,在线搜索MiniProfilter,如下图
安装完成后,在global文件中加上相应代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using StackExchange.Profiling;
using StackExchange.Profiling.EntityFramework6;
namespace MvcDemo
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
MiniProfilerEF6.Initialize();
}
protected void Application_BeginRequest()
{
MiniProfiler.Start();
}
protected void Application_EndRequest()
{
MiniProfiler.Stop();
}
}
}
start方法中添加Miniprofilter法eginRequest和EndRequest方
中添加监控起始代码。
二、配置
在web.config中的system.webServer节点中添加以下代码
<system.webServer>
<handlers>
<add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
</handlers>
</system.webServr>
然后在模板页添加渲染代码,如图
其中的参数是一个枚举类型用于定位监控显示
可以为空,默认定位左上角。运行网站效果如下图
三、监控具体方法
直接上代码
public ActionResult Index(string sortBy,string sortDesc,string searchString,int? page)
{
sortDesc = sortDesc ?? "Y";
ViewBag.sortDesc = "Y".Equals(sortDesc) ? "N" : "Y";
var miniProfilter = MiniProfiler.Current;
using (miniProfilter.Step("获取用户列表"))
{
var users = from u in db.SysUsers select u;
if (!string.IsNullOrEmpty(searchString))
{
users = users.Where(u => u.UserName.Contains(searchString));
}
switch (sortDesc)
{
case "Y":
users = users.OrderByDescending(u => u.UserName);
break;
case "N":
users = users.OrderBy(u => u.UserName);
break;
}
int pageSize = 2;
int pageNumber = page ?? 1;
return View(users.ToPagedList(pageNumber,pageSize));
}
}
Mark.