Entity Framework爲咱們提供了很大的方便,但有時候,咱們想看看EF生成的Sql語句究竟是怎樣的,一種方式是咱們能夠啓用Sql Server Profer工具。今天介紹另一種方式,很是簡單,能夠監聽EF執行的每條Sql語句,並且也能夠自定義在執行語句前,執行語句完成後的動做。經過這種方式也能夠很是方便的去監聽系統的運行日誌。app
完成這個功能,須要引入二個第三方的組件,分別是Clutch.dll和Clutch.Diagnostics.EntityFramework.dll(網上能夠下載到)。引入以後,只須要實現IDbTracingListener接口:工具
public class TestListener : IDbTracingListener
{
public void CommandExecuted(DbTracingContext context)
{
Debug.WriteLine(context.Command.CommandText);
}
public void CommandExecuting(DbTracingContext context)
{
//throw new NotImplementedException();
}
public void CommandFailed(DbTracingContext context)
{
//throw new NotImplementedException();
}
public void CommandFinished(DbTracingContext context)
{
//throw new NotImplementedException();
}
public void ReaderFinished(DbTracingContext context)
{
//throw new NotImplementedException();
}
}
接口中的幾個方法,分別是Sql語句執行前,執行完成後等要執行的方法,你能夠在這個方法裏面作任何事.更關鍵的是它的參數DbTracingContext裏面有你想要的一切,包括生成的Sql語句.spa
把這個接口實現後,你只須要在Context裏面加上監聽便可.日誌
DbTracing.Enable();
DbTracing.AddListener(new TestListener());
後面你執行的全部Sql語句,均可以在這裏面看到.code