2010-01-24 51 views
1

如何获取由LinqToSql生成的更新方法的sql?如何获取由LinqToSql生成的sql更新方法?

我用下面的代码显示在VS2008的调试输出窗口由LinqToSql生成的SQL,但它只是变得生成的SQL SELECT方法,

我怎么能找到被LinqToSql生成的SQL更新方法?

我知道Sql Server Profiler和LinqPad可以得到它(生成的sql-update),但我想在VS2008中显示它们或将它们记录到文件中。

public partial class Linq2 : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      DemoDataContext ctx = new DemoDataContext(); 

      // Then attach it to the Log property of your DataContext... 
      ctx.Log = new DebugTextWriter(); 

      var product = ctx.Products.FirstOrDefault(); 

      product.ProductName = "NewName1"; 

      ctx.SubmitChanges();    

     } 
    } 

    // Add this class somewhere in your project... 
    public class DebugTextWriter : System.IO.TextWriter 
    { 
     public override void Write(char[] buffer, int index, int count) 
     { 
      System.Diagnostics.Debug.Write(new String(buffer, index, count)); 
     } 

     public override void Write(string value) 
     { 
      System.Diagnostics.Debug.Write(value); 
     } 

     public override Encoding Encoding 
     { 
      get { return System.Text.Encoding.Default; } 
     } 
    } 

我也得到在VS2008调试输出窗口中的SQL选择查询:

SELECT TOP (1) [t0].[Id], [t0].[ProductName] …… 
FROM [dbo].[Products] AS [t0] 
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.1 

回答

0

谢谢你所有的答案。 我发现Linq To SQL Profiler来解决这个问题。

1

你的数据库上下文对象有一个登录方法,你可以重写。您的完整Update语句以及Linq-To-SQL生成的每个SQL命令都可以通过此Log方法捕获。我知道这是有效的,因为我用它来捕获我们应用程序中的所有查询。请记住,L2S可以向Log方法发送相当数量的输出,因此请确保将其全部捕获。你的Update语句在某处。

+0

你能提供更多的细节吗?我在上下文中找不到sql语句.Log – Mike108 2010-01-25 02:50:08

+0

上下文对象有一个System.IO.TextWriter方法,您可以将侦听器附加到该方法。在我的情况下,我创建了一个名为SQLLogWriter的StringWriter类,并执行以下操作:context.Log = SQLLogWriter。所有的L2S输出都会发给这位作者。 – 2010-01-25 12:40:49

+0

你能提供代码吗?我使用了一些StringWriter类,它们只记录L2S的sql select语句。你确定你可以将sql更新语句记录到StringWriter类吗? – Mike108 2010-01-25 22:07:02