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

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

一.控制台程序(Console)dataContext.Log = Console.Out;二.利用GetCommand方法

dataContext.GetCommand(query).CommandText;

三.使用LINQPad (官方网站)

LINQPad支持C# 3.0 和 Framework 3.5的全部功能:LINQ to SQL

LINQ to Objects

LINQ to XML

四.LINQ to SQL Debug Visualizer

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

安装方法

1. 关闭 VS2008。

2. 将压缩包中的 SqlServerQueryVisualizer.dll 拷贝到 \Program Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers。

3. 重启 VS2008 即可。

五.DebuggerWriter工具类

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

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

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

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

源码:

usingSystem;

usingSystem.Diagnostics;

usingSystem.Globalization;

usingSystem.IO;

usingSystem.Text;

namespaceVandermotten.Diagnostics

{

/**///Implements afor writing information to the debugger log.

//////

publicclassDebuggerWriter : TextWriter

{

privateboolisOpen;

privatestaticUnicodeEncoding encoding;

privatereadonlyintlevel;

privatereadonlystringcategory;

/**///Initializes a new instance of theclass.

///

publicDebuggerWriter()

:this(0, Debugger.DefaultCategory)

{

}

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

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

publicDebuggerWriter(intlevel,stringcategory)

:this(level, category, CultureInfo.CurrentCulture)

{

}

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

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

publicDebuggerWriter(intlevel,stringcategory, IFormatProvider formatProvider)

:base(formatProvider)

{

this.level=level;

this.category=category;

this.isOpen=true;

}

protectedoverridevoidDispose(booldisposing)

{

isOpen=false;

base.Dispose(disposing);

}

publicoverridevoidWrite(charvalue)

{

if(!isOpen)

{

thrownewObjectDisposedException(null);

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

}

publicoverridevoidWrite(stringvalue)

{

if(!isOpen)

{

thrownewObjectDisposedException(null);

}if(value!=null)

{

Debugger.Log(level, category, value);

} }

publicoverridevoidWrite(char[] buffer,intindex,intcount)

{

if(!isOpen)

{

thrownewObjectDisposedException(null);

}if(buffer==null||index<0||count<0||buffer.Length-index

{

base.Write(buffer, index, count);//delegate throw exception to base class} Debugger.Log(level, category,newstring(buffer, index, count));

}

publicoverrideEncoding Encoding

{

get

{

if(encoding==null)

{

encoding=newUnicodeEncoding(false,false);

}returnencoding;

} }

publicintLevel

{

get{returnlevel; } }

publicstringCategory

{

get{returncategory; } } }}

六.将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类的源码:

//原文:http://www.yaosansi.com/post/1380.htmlusingSystem;

usingSystem.Collections.Generic;

usingSystem.Text;

usingSystem.IO;

namespaceYaosansi.IO

{

/**///文件操作

///

publicclassFileLog : TextWriter

{

构造函数#region构造函数

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

publicFileLog(stringfileName)

            :this(fileName,string.Empty,false)

{

        }

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

publicFileLog(stringfileName,stringfilePath,booldeleteExistingFile):this(fileName,filePath,long.MaxValue)

{

if(deleteExistingFile)

{

                DeleteFile();

            }        }

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

publicFileLog(stringfileName,stringfilePath,longfileSize)

{

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

重写TextWriter#region重写TextWriter

publicoverrideEncoding Encoding

{

get

{

returnnewUnicodeEncoding(false,false);

            }        }

publicoverridevoidWrite(charvalue)

{

            WriteFile(value.ToString());

        }

publicoverridevoidWrite(stringvalue)

{

if(value!=null)

{

                WriteFile(value);

            }        }

publicoverridevoidWrite(char[] buffer,intindex,intcount)

{

if(buffer==null||index<0||count<0||buffer.Length-index

{

base.Write(buffer, index, count);

            }            WriteFile(newstring(buffer, index, count));

        }

#endregion

属性#region属性

/**///文件名

///

publicstringFileName{set;get; }

/**///获取文件全名[包含路径]

///

publicstringFullFileName

{

get

{

returnFilePath+"\\"+FileName;

            }        }

/**///定义文件大小

///

publiclongFileSize{set;get; }

/**///文件路径;

///

publicstringFilePath

{

set;

get;

        }

/**///FileLog Factory

///

publicstaticFileLog Out

{

get

{

returnnewFileLog("");

            }        }

#endregion

方法#region方法

/**///删除文件

//////

publicboolDeleteFile()

{

boolsucceed=false;

try

{

if(File.Exists(FullFileName))

{

                    File.Delete(FullFileName);

                    succeed=true;

                }            }

catch{ }returnsucceed;

        }

/**///仅记录当前时间及分隔符

///

publicvoidWirteTime()

{

stringmessage="\r\n-------------------------------------------------------\r\n"+"时间:"+DateTime.Now.ToString()+"\r\n"+"-------------------------------------------------------";

            WriteFile(message);

        }

/**///写文件

//////

publicvoidWriteFile(stringMessage)

{

            StreamWriter sw=null;

try

{

//如果文件目录不存在,则创建if(!Directory.Exists(FilePath))

{

                    Directory.CreateDirectory(FilePath);

                }//超过一定大小自动删除文件if(FileSize!=long.MaxValue)

{

                    FileInfo finfo=newFileInfo(FullFileName);

if(finfo.Exists&&finfo.Length>FileSize)

{

                        finfo.Delete();

                    }                }if(!File.Exists(FullFileName))

{

                    sw=File.CreateText(FullFileName);

                }else

{

                    sw=File.AppendText(FullFileName);

                }                sw.WriteLine(Message);

                sw.Flush();

            }catch(Exception ee)

{

                Console.WriteLine("文件没有打开,详细信息如下:"+ee.ToString());

throw(newException("文件没有打开,详细信息如下:"+ee.ToString()));

            }finally

{

                sw.Close();

                sw.Dispose();

            }        }#endregion

    }}

mysql 构造 linq语句_[转]查看LINQ生成SQL语句的几种方法相关推荐

  1. ef 执行mysql语句_在EF中执行SQL语句

    一.为什么要在EF中执行SQL语句 使用EF操作数据库,可以避免写SQL语句,完成使用Linq实现,但为什么还要在EF中执行SQL语句呢.如果要写SQL语句,完全可以使用ADO.NET来操作数据库.这 ...

  2. mysql函数 动态语句_自定义函数动态执行SQL语句

    Oracle 动态SQL有两种写法:用 DBMS_SQL 或 execute immediate,建议使用后者. DDL 和 DML Sql代码 收藏代码 /*** DDL ***/ begin EX ...

  3. mysql query语句_使用mysql_query()函数执行SQL语句

    mysql_query()函数 PHP MySQL 函数库中,mysql_query() 函数用于向 MySQL 发送并执行 SQL 语句. 对于没有数据返回结果集的 SQL ,如 UPDATE.DE ...

  4. mysql字段排序语句_数据库字段排序的SQL语句

    简明现代魔法 -> 数据库技术 -> 数据库字段排序的SQL语句 数据库字段排序的SQL语句 2009-09-17 将字段依次写在order by 后面即可 , 中间用逗号隔开. sele ...

  5. mybatisplus执行sql语句_一条更新的SQL语句是如何执行的?

    提出问题 UPDATE student SET score = score + 1 WHERE uid = 666; 以上就是一条最简单的SQL更新语句,想要知道上面这句SQL语句是怎么执行的先要了解 ...

  6. python制作表格的语句_python读取excel表格生成sql语句 第一版

    由于单位设计数据库表·,都用sql.不知道什么原因不用 powerdesign或者ermaster工具,建表很痛苦  作为程序猿当然要想办法解决,用Python写一个程序解决 需要用到 xlrd li ...

  7. mysql 数据库连表查询语句_数据库连表查询sql语句

    {"moduleinfo":{"card_count":[{"count_phone":1,"count":1}],&q ...

  8. 命令行客户端MySQL基本命令的使用(登录、登出、数据库操作的SQL语句、表结构的SQL语句、表数据操作的SQL语句)

    1. 登录和登出数据库 登录数据库: 输入下面命令: mysql -uroot -p 说明: -u 后面是登录的用户名  [写成-u root也是可以的] -p 后面是登录密码, 如果不填写, 回车之 ...

  9. oracle 查看用户日志,Oracle查看用户操作sql语句以及数据库日志

    --查看日志文件 select member from v$logfile; --查看表空间使用情况 SELECT SUM(bytes) / (1024 * 1024) AS free_space, ...

最新文章

  1. QT 中QTimer 和 startTimer()的区别
  2. 扩增子文献笔记1白杨内生和根际微生物组在不同生态位存在特异的群落结构
  3. Web容器启动中执行某个Java类
  4. c++runtime error单调栈
  5. python科学编程入门书_Python数据科学零基础一本通
  6. NetAdvangate Infragisticss 控件在工程移动到别的机器上,引用失效问题
  7. ICS/SCADA 系统的对比
  8. Python3网络爬虫开发实战,Appium+mitmdump 爬取京东商品
  9. 第1章 Ext JS开发基本环境准备与项目创建[3/4]
  10. WCF中如何修改MaxItemsInObjectGraph的限制
  11. 多边形交叉区域计算面积_用什么算法来找到多边形与圆之间的交叉区域?
  12. AE zoom to selected 地图刷新
  13. linux系统svn安装教程,Linux下SVN安装配置
  14. 前端实现动画的7种方式
  15. Altium net has no driving source问题
  16. 〈西游记〉中所有插曲、主题曲
  17. 俄罗斯方块游戏的算法
  18. abaqus的python安装文件在哪_拓展abaqus python 模块
  19. 读取JPEG文件的压缩质量/质量因子参数
  20. 电脑查询域名对应IP的过程

热门文章

  1. IP探针系统 信息探针
  2. Markdown技能树
  3. 金蝶总账,报表操作流程
  4. 菲尼克斯模块QUINT4-DIODE/12-24DC/2X20/1X40
  5. 一着惊海天教学课件PPT模板
  6. 兼职收入过w后,我决定把我所有的接单途径告诉你
  7. 【TypeScript专题】之类型断言
  8. 高频宽带功率放大器(频率:10KHZ-1MHZ 功率:400-800W)
  9. ON1 Photo RAW 2018 for Mac v2018.1 照片编辑 PS滤镜插件
  10. Matlab论文插图绘制模板—三维柱状图