C# 如何从 LINQ DataContext.SubmitChanges() 获取 TSQL 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/637117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:14:26  来源:igfitidea点击:

How to get the TSQL Query from LINQ DataContext.SubmitChanges()

c#linqlinq-to-sqldatacontextsubmitchanges

提问by tsilb

I'm using Linq to SQL. I have a DataContext against which I am .SubmitChanges()'ing. There is an error inserting the identity field, and I'd like to see the query it's using to insert this identity field.

我正在使用 Linq to SQL。我有一个 DataContext,我正在针对它 .SubmitChanges()'ing。插入身份字段时出错,我想查看它用于插入此身份字段的查询。

I don't see the query itself within the quickwatch; where can I find it from within the debugger?

我在 quickwatch 中没有看到查询本身;我在哪里可以从调试器中找到它?

采纳答案by Taha Rehman Siddiqui

There is actually a very simple answer to your question

你的问题其实有一个非常简单的答案

Just paste this in your watch window

只需将其粘贴到您的观察窗口中

((System.Data.Objects.ObjectQuery)myLinqQueryVar).ToTraceString()

回答by geofftnz

Run SQL Profiler if you have it. It'll show all traffic to your database, including SQL command text.

如果有,请运行 SQL Profiler。它将显示数据库的所有流量,包括 SQL 命令文本。

回答by Portman

Lots of people have been writing their own "DebugWriter" and attaching it like so:

很多人一直在编写自己的“DebugWriter”并像这样附加它:

// Add this class somewhere in your project...
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; }
   }
}

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

This will output everything that Linq-to-Sql is doing into Visual Studio's debug window.

这会将 Linq-to-Sql 正在执行的所有操作输出到 Visual Studio 的调试窗口中。

回答by Kev

Further to Portman's answer, if you're a console application it's as simple as:

进一步波特曼的回答,如果你是一个控制台应用程序,它很简单:

myDataContext.Log = Console.Out;

Or you could use something like Linq2SQL Profiler which is a rather excellent tool and in fact the right tool for the job:

或者你可以使用类似 Linq2SQL Profiler 的东西,它是一个相当出色的工具,实际上是适合这项工作的工具:

Linq to SQL Profiler - Real-time visual debugger for Linq to SQL

Linq to SQL Profiler - Linq to SQL 的实时可视化调试器

回答by bopapa_1979

I agree that Linq to SQL Profiler is the right tool for this job. But if you don't want to spend the money or just need to do something simple, I like the DebugTextWriter approach.

我同意 Linq to SQL Profiler 是适合这项工作的工具。但是如果你不想花钱或者只需要做一些简单的事情,我喜欢 DebugTextWriter 方法。

After reading this question I went off looking for something more robust. It turns out Damien Guard also wrote a very nice articleabout building different writers to deal with different things like outputting to Memory, Debug, a File, Multiple Destinations, or even using simple Delegates.

阅读完这个问题后,我开始寻找更强大的东西。事实证明,Damien Guard 还写了一篇非常好的文章,关于构建不同的编写器来处理不同的事情,例如输出到内存、调试、文件、多个目的地,甚至使用简单的委托。

I wound up using a couple of his ideas and writing an ActionTextWriter that can handle more than one delegate, and I thought I would share it here:

我最终使用了他的一些想法并编写了一个可以处理多个委托的 ActionTextWriter,我想我会在这里分享它:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Writers
{
    public class ActionTextWriter : TextWriter
    {
        protected readonly List<Action<string>> Actions = new List<Action<string>>();

        public ActionTextWriter(Action<string> action)
        {
            Actions.Add(action);
        }

        public ActionTextWriter(IEnumerable<Action<string>> actions)
        {
            Actions.AddRange(actions);
        }

        public ActionTextWriter(params Action<string>[] actions)
        {
            Actions.AddRange(actions);
        }

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

        public override void Write(char[] buffer, int index, int count)
        {
            Write(new string(buffer, index, count));
        }

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

        public override void Write(string value)
        {
            if (value == null)
            {
                return;
            }

            foreach (var action in Actions)
            {
                action.Invoke(value);
            }
        }
    }
}

You can add as many actions as you like. This example writes to a log file and the Console in Visual Studio via Debug.Write:

您可以根据需要添加任意数量的操作。此示例通过 Debug.Write 写入日志文件和 Visual Studio 中的控制台:

// Create data context
var fooDc = new FooDataContext();

// Create writer for log file.
var sw = new StreamWriter(@"C:\DataContext.log") {AutoFlush = true};

// Create write actions.
Action<string> writeToDebug = s => Debug.Write(s);
Action<string> writeToLog = s => sw.Write(s);

// Wire up log writers.
fooDc.Log = new ActionTextWriter(writeToDebug, writeToLog);

And of course if you want to make simpler ones to use off the cuff, you can always extendActionTextWriter... write the generic approach and reuse, right?

当然,如果您想制作更简单的袖口使用,您可以随时扩展ActionTextWriter ...编写通用方法并重用,对吗?

using System.Diagnostics;
using System.IO;

namespace Writers
{
    public class TraceTextWriter : ActionTextWriter
    {
        public TraceTextWriter()
        {
            Actions.Add(s => Trace.Write(s));
        }
    }

    public class FileTextWriter : ActionTextWriter
    {
        public FileTextWriter(string path, bool append = false)
        {
            var sw = new StreamWriter(path, append) {AutoFlush = true};
            Actions.Add(sw.Write);
        }
    }
}

回答by Loureiro

FooDataContext dc = new FooDataContext();

StringBuilder sb = new StringBuilder();
dc.Log = new StringWriter(sb);

var result=from r in dc.Tables select d;

.....
string query=sb.ToString();