当前位置: 首页 > 工具软件 > NPoco > 使用案例 >

.net 监控 npoco orm 的 sql 语句

蔚宏大
2023-12-01

1、在 nuget.org 安装 Profiler.AspNetCore.Mvc

PM> Install-Package MiniProfiler.AspNetCore.Mvc

2、在 Startup.cs 中修改 ConfigureServices

public void ConfigureServices(IServiceCollection services)
        {
           
            services.AddControllersWithViews();
            // miniprofile conf.
            services.AddMiniProfiler(options => 
            {
                options.PopupRenderPosition = RenderPosition.BottomLeft;
                options.PopupShowTimeWithChildren = true;

            });
        }

3、在 Startup.cs 中修改 Configure

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
       if (env.IsDevelopment())
       {
           app.UseDeveloperExceptionPage();
       }

       app.UseMiniProfiler();
       //重点这个
       app.UseRouting();

       app.UseEndpoints(endpoints =>
       {
           //endpoints.MapGet("/", async context =>
           //{
           //    await context.Response.WriteAsync("Hello World!");
           //});
           endpoints.MapControllerRoute(
               name:"Home",
               pattern:"{controller=Home}/{action=Index}/{id?}");
       });
   }

4、重写 NPOCO 的 Database 中 OnConnectionOpened 方法(官网 wike 这个地方是错误的 2020.2.25 记录)

public class MyDatabase: Database
{
    public MyDatabase(string connectionString) : base(connectionString, DatabaseType.SqlServer2012, SqlClientFactory.Instance) { }
    protected override DbConnection OnConnectionOpened(DbConnection conn)
    {
        return new ProfiledDbConnection(conn, MiniProfiler.Current);
    }
}

5、使用 (稍微不同,我在 MyDatabase 中封装了一下)

 public IEnumerable<LoginLog> Find() {
    using (var db = new MyDatabase("db")
     {
         var query = db.Fetch<LoginLog>();
         return query;
     }
 }

6、_ViewImports.cshtml 添加对 Profiler 的支持

@using Test_MiniProfile
@using StackExchange.Profiling
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, MiniProfiler.AspNetCore.Mvc

7、在母版页合适的地方展示 Profiler

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - BaseMvcWeb</title>
</head>
<body>
         @RenderBody()
        <mini-profiler />
</body>
</html>

官网文档:https://github.com/schotime/NPoco/wiki/Debugging-and-Profiling
参考:https://my.oschina.net/TOW/blog/3171858

 类似资料: