最近在使用Linq To SQL的時候,為了了解不同Linq語句對性能造成的不同影響,需要獲得Linq To SQL生成的SQL語句。
如果是在桌面程序中,只需要
_context.Log = Console.Out;
即可在控制台輸出SQL語句。可是在ASP.Net中又該怎麼辦呢?
這時我想起了StringWriter。用它就可以代替Console.Out幫我們接收輸出的日志,保存在一個StringBuilder裡。
於是構造一個輔助類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
namespace Clowwindy.Models
{
public static class LogHelper
{
public static StringBuilder Log = new StringBuilder();
public static TextWriter In = new StringWriter(Log);
public static string GetAllLog()
{
In.Flush();
return Log.ToString();
}
public static void Clean()
{
Log = new StringBuilder();
In = new StringWriter(Log);
}
}
}
再添加一個頁面log.ASPx,用來顯示日志:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Log.ASPx.cs" Inherits="Clowwindy.Log" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xHtml1-transitional.dtd">
<html XMLns="http://www.w3.org/1999/xHtml" >
<head runat="server">
<title>SQL Log</title>
</head>
<body>
<form id="form1" runat="server">
<ASP:Button ID="btn_Clean" runat="server" Text="清空"
onclick="btn_Clean_Click"/>
<div>
<asp:Literal ID="Literal1" runat="server"></ASP:Literal>
</div>
</form>
</body>
</Html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Clowwindy.Models;
namespace Clowwindy
{
public partial class Log : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UserHostAddress != "127.0.0.1")
{
Response.End();
return;
}
Literal1.Text = LogHelper.GetAllLog().Replace("n","n<br/>");
}
protected void btn_Clean_Click(object sender, EventArgs e)
{
LogHelper.Clean();
Literal1.Text = null;
}
}
}
最後在所有new DataContext的地方加上_context.Log = LogHelper.In:
public Repository()
{
_context = new TDataContext();
_context.Log = LogHelper.In;
}
打開log.ASPx,即可看到之前執行的SQL語句