Chinaunix首页 | 论坛 | 博客
  • 博客访问: 80452
  • 博文数量: 64
  • 博客积分: 1545
  • 博客等级: 上尉
  • 技术积分: 392
  • 用 户 组: 普通用户
  • 注册时间: 2012-10-23 15:23
文章分类

全部博文(64)

文章存档

2013年(1)

2012年(63)

我的朋友

分类: 嵌入式

2012-11-23 21:56:22

记录LINQ生成的SQL语句是常用的调试方式,而且能根据需要来优化LINQ生成的SQL语句,更能了深入的了解LINQ.

DataContext的Log属性来将LINQ to SQL生成的SQL语句格式化.

一.控制台程序(Console)

dataContext.Log = Console.Out;

二.利用GetCommand方法

dataContext.GetCommand(query).CommandText;

三.使用LINQPad ()


更多介绍请参考李永京学习LINQ工具:LINQPad

下载地址:

四.LINQ to SQL Debug Visualizer

ScottGu的LINQ to SQL Debug Visualizer可以在Debug过程中查看SQL语句.

介绍:http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx

下载:http://www.scottgu.com/blogposts/linqquery/SqlServerQueryVisualizer.zip

安装方法
1. 关闭 VS2008。
2. 将压缩包中的 SqlServerQueryVisualizer.dll 拷贝到 \Program Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers。
3. 重启 VS2008 即可。

五.DebuggerWriter工具类

由于Console.Out方法在ASP.NET程序不起作用.

已经创建好了一个这个工具类, 你只要使用这样的语法:

MyDataContext db = new MyDataContext();db.Log = new DebuggerWriter(); 

asp.net可以选择将Log信息直接发送到Debug的输出窗口.

源码:

using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;

namespace Vandermotten.Diagnostics
{
    
/// 
    
/// Implements a  for writing information to the debugger log.
    
/// 

    
/// 

    public class DebuggerWriter : TextWriter
    
{
        
private bool isOpen;
        
private static UnicodeEncoding encoding;
        
private readonly int level;
        
private readonly string category;

        
/// 
        
/// Initializes a new instance of the  class.
        
/// 

        public DebuggerWriter()
            : 
this(0, Debugger.DefaultCategory)
        
{
        }


        
/// 
        
/// Initializes a new instance of the  class with the specified level and category.
        
/// 

        
/// A description of the importance of the messages.
        
/// The category of the messages.

        public DebuggerWriter(int level, string category)
            : 
this(level, category, CultureInfo.CurrentCulture)
        
{
        }


        
/// 
        
/// Initializes a new instance of the  class with the specified level, category and format provider.
        
/// 

        
/// A description of the importance of the messages.
        
/// The category of the messages.
        
/// An  object that controls formatting.

        public DebuggerWriter(int level, string category, IFormatProvider formatProvider)
            : 
base(formatProvider)
        
{
            
this.level = level;
            
this.category = category;
            
this.isOpen = true;
        }


        
protected override void Dispose(bool disposing)
        
{
            isOpen 
= false;
            
base.Dispose(disposing);
        }


        
public override void Write(char value)
        
{
            
if (!isOpen)
            
{
                
throw new ObjectDisposedException(null);
            }

            Debugger.Log(level, category, value.ToString());
        }


        
public override void Write(string value)
        
{
            
if (!isOpen)
            
{
                
throw new ObjectDisposedException(null);
            }

            
if (value != null)
            
{
                Debugger.Log(level, category, value);
            }

        }


        
public override void Write(char[] buffer, int index, int count)
        
{
            
if (!isOpen)
            
{
                
throw new ObjectDisposedException(null);
            }

            
if (buffer == null || index < 0 || count < 0 || buffer.Length - index < count)
            
{
                
base.Write(buffer, index, count); // delegate throw exception to base class
            }

            Debugger.Log(level, category, 
new string(buffer, index, count));
        }


        
public override Encoding Encoding
        
{
            
get
            
{
                
if (encoding == null)
                
{
                    encoding 
= new UnicodeEncoding(falsefalse);
                }

                
return encoding;
            }

        }


        
public int Level
        
{
            
get return level; }
        }


        
public string Category
        
{
            
get return category; }
        }

    }

}

六.将LINQ to SQL生成的SQL语句写入日志文件

DataContext.Log是System.IO.TextWriter类型,所以你可以用以下的方法来做.

StreamWriter sw = new StreamWriter(

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "log.txt"));

dBLinqDataContext.Log = sw;

var query = dataContext.Customers.Single(c=>c.CustomerID.Contains("s"))

.Skip(0).Take(10).ToList();

sw.Flush(); sw.Close();

但以上方法有个缺点,就是需要在每个实现的方法中都写这么多代码.使用起来太不方便.参照dataContext.Log = Console.Out的表现形式

由是有了FileLog类.(当然,FileLog类除了此功能还有一些基本的记录日志的方法)

使用时直接dataContext.Log = Yaosansi.IO.FileLog.Out;即可. 默认会在桌面上生成一个名叫UnNameFile.txt的文件.

当然如果你不想使用默认的文件名和路径也可以使用dataContext.Log =new Yaosansi.IO.FileLog("FileName")的方式.

下面是FileLog类的源码:

//原文:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Yaosansi.IO
{
    
/// 
    
/// 文件操作
    
/// 

    public class FileLog : TextWriter
    
{
        
#region 构造函数

      
        
/// 
        
/// 
        
/// 

        
/// 文件名[文件路径使用默认路径]

        public FileLog(string fileName)
            : 
this(fileName,string.Empty,false)
        
{
        }


        
/// 
        
/// 
        
/// 

        
/// 文件名
        
/// 文件路径
        
/// 是否删除已经存在的文件

        public FileLog(string fileName,string filePath, bool deleteExistingFile):this(fileName,filePath,long.MaxValue)
        
{
            
if (deleteExistingFile)
            
{
                DeleteFile();
            }

        }


        
/// 
        
/// 
        
/// 

        
/// 文件名
        
/// 文件路径
        
/// 文件大小[单位:bytes]超出此大小将自动删除文件(使用longong.MaxValue例外)
        
/// 

        public FileLog(string fileName, string filePath, long fileSize)
        
{
            
if (!string.IsNullOrEmpty(fileName))
            
{
                FileName 
= fileName;
            }

            
else
            
{
                FileName 
= "UnNameFile.txt";
            }

            
if (!string.IsNullOrEmpty(filePath))
            
{
                FilePath 
= filePath;
            }

            
else
            
{
                FilePath 
= Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            }

            FileSize 
= fileSize;
        }

        
#endregion


        
#region 重写TextWriter


        
public override Encoding Encoding
        
{
            
get
            
{
                
return new UnicodeEncoding(falsefalse);
            }

        }



        
public override void Write(char value)
        
{
            WriteFile(value.ToString());
        }


        
public override void Write(string value)
        
{
            
if (value != null)
            
{
                WriteFile(value);
            }
阅读(1456) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~