熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

ASP.NET中顯示Linq To SQL輸出的SQL語句

2022-06-13   來源: .NET編程 
        最近在使用Linq To SQL的時候為了了解不同Linq語句對性能造成的不同影響需要獲得Linq To SQL生成的SQL語句

  

  如果是在桌面程序中只需要

  

  _contextLog = ConsoleOut;

  即可在控制台輸出SQL語句可是在ASPNET中又該怎麼辦呢?

  

  這時我想起了StringWriter用它就可以代替ConsoleOut幫我們接收輸出的日志保存在一個StringBuilder裡

  

  於是構造一個輔助類

  

  using System;

  using SystemCollectionsGeneric;

  using SystemLinq;

  using SystemWeb;

  using SystemIO;

  using SystemText;

  

  namespace ClowwindyModels

  {

  public static class LogHelper

  {

  public static StringBuilder Log = new StringBuilder();

  public static TextWriter In = new StringWriter(Log);

  public static string GetAllLog()

  {

  InFlush();

  return LogToString();

  }

  public static void Clean()

  {

  Log = new StringBuilder();

  In = new StringWriter(Log);

  }

  }

  }

  

  再添加一個頁面logaspx用來顯示日志

  

  

  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Log.aspx.cs" Inherits="Clowwindy.Log" %>

  

  

  

  

  

  

  

  

  

  onclick=btn_Clean_Click/>

  

  

  

  

  

  

  

  

  using System;

  using SystemCollectionsGeneric;

  using SystemLinq;

  using SystemWeb;

  using SystemWebUI;

  using SystemWebUIWebControls;

  using ClowwindyModels;

  

  namespace Clowwindy

  {

  public partial class Log : SystemWebUIPage

  {

  protected void Page_Load(object sender EventArgs e)

  {

  if (RequestUserHostAddress != )

  {

  ResponseEnd();

  return;

  }

  LiteralText = LogHelperGetAllLog()Replace(\n\n
);

  }

  

  protected void btn_Clean_Click(object sender EventArgs e)

  {

  LogHelperClean();

  LiteralText = null;

  }

  }

  }

  

  最後在所有new DataContext的地方

  加上_contextLog = LogHelperIn:

  

  

  public Repository()

  {

  _context = new TDataContext();

  _contextLog = LogHelperIn;

  }

  打開logaspx即可看到之前執行的SQL語句


From:http://tw.wingwit.com/Article/program/net/201311/11979.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.