如何允许 MiniProfiler 查看 EF DbContext.Database.SqlQuery 查询

How to allow MiniProfiler to see EF DbContext.Database.SqlQuery queries

我正在调整一些耗时过长的 Entity Framework 查询,在某些情况下我会通过 dbContext.Database.SqlQuery<Entity>(sql, [parameters]).

执行原始 SQL

但是,这些查询不再显示在 profiler.Step 文本旁边的 MiniProfiler 中。我需要做什么才能让他们再次出现?

我进行了一些搜索,但发现很少。因为我通过 EF 进行查询,所以我认为它会起作用。我很确定我在 MiniProfiler 中看到了 Dapper 查询,所以显然随机查询可以交给 MiniProfiler,我只是不知道我做错了什么。

请看下图中的红色椭圆:它应该显示时间,我可以点击查看 SQL。此外,正下方的 SQL 时间现在忽略了我已转换的查询。

我所做的唯一更改是转换这样的查询:

return db.Blornk.Where(b => b.HasPlutonium = @flag);

给这样的人:

return db.Database.SqlQuery<Blornk>(@"
   SELECT *
   FROM Blornk
   WHERE HasPlutonium = @flag",
   new SqlParameter("@flag", flag)
);

当然,EF 很迟钝,这就是我首先进行更改的原因,但即使是同一个查询也没关系,我只需要知道如何让 MiniProfiler 再次快乐。

根据 the MiniProfiler authors,由于 MiniProfiler 连接到 EF6 的方式,它无法完成。显示了一个解决方法,但它需要通过配置文件连接手动发送我们的查询。

There is a workaround. The code below uses Dapper and the datacontext connection to create a ProfiledDbConnection, which accepts the same sql, returns the same result and does record the sql.

using (MiniProfiler.Current.Step("Get Count using ProfiledConnection - sql recorded"))
{
    using (var conn = new ProfiledDbConnection(context.Database.Connection, MiniProfiler.Current))
    {
        conn.Open();
        newCount = conn.Query<int>(sql).Single();
        conn.Close();
    }
}