[英]Inject debug information into Entity Framework queries
我們在我們的商店中使用 Dapper 和 EF,並且 Dapper 證明在出現問題時在調試 SQL 服務器中的查詢方面非常有幫助。 我們不只是提交原始 SQL,而是創建了一個瘦裝飾器,它還添加了一些上下文信息(源)作為 SQL 注釋,例如
/* Foo.Bar.GetOrders() */ SELECT * FROM Order WHERE orderId > 123
這使我們的 DBA 和開發人員能夠非常快速地反應並找到問題的根源,如果我們有錯誤的 DB 調用,或引入性能下降(我們每天有數十萬個 DB 調用,因此一個錯誤的查詢可能會導致相當多的損害)。
我們也想與 EF 一起做這件事。 它不必是 SQL 注釋,而是某種鈎子,以便提供隨調用提交的元信息。 知道這是否可能嗎?
謝謝你的建議
菲利普
事實證明,這在 EF 6 中變得非常容易。所需要的只是IDbCommandInterceptor的實現,它允許我使用自定義 (SQL) 注釋來擴充提交的 SQL。 該注釋將出現在數據庫日志中,從而從 DBA 端啟用調試/跟蹤。
public class DebugCommentInterceptor : IDbCommandInterceptor
{
public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
command.CommandText = "/* TRACING INFORMATION GOES HERE */ " + command.CommandText;
}
public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
command.CommandText = "/* TRACING INFORMATION GOES HERE */ " + command.CommandText;
}
public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
}
public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
}
public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
}
public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
}
}
為了讓上面的攔截器可以運行,我簡單地用靜態DbInterception類注冊了它:
DbInterception.Add(new DebugCommentInterceptor());
如果您使用 EF Core,則可以使用查詢標簽。
var nearestFriends =
(from f in context.Friends.TagWith("This is my spatial query!")
orderby f.Location.Distance(myLocation) descending
select f).Take(5).ToList();
有新的 linq .TagWith('')
,它將生成 Sql 查詢:
-- This is my spatial query!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.