开发者

How to get the sql update method generated by LinqToSql?

开发者 https://www.devze.com 2022-12-18 10:02 出处:网络
How to get thesql generated by LinqToSql for update method? I use the following code to show the sql generated by LinqToSql in VS200开发者_运维技巧8\'s debug output window, but it only gets the sql s

How to get the sql generated by LinqToSql for update method?

I use the following code to show the sql generated by LinqToSql in VS200开发者_运维技巧8's debug output window, but it only gets the sql select method generated,

how can I find the sql update method that was generated by LinqToSql?

I know the Sql Server Profiler and LinqPad can get it(the sql-update generated), but I want to show them in VS2008 or Log them to a file.

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; }
        }
    }

And I get the sql-select query in the VS2008 debug output window:

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


Your Database context object has a Log method that you can override. Your full Update statement, and every SQL command generated by Linq-To-SQL, can be captured via this Log method. I know this works because I use it to capture all our queries in our app. Just keep in mind that L2S can send a fair amount of output to the Log method, so make sure to capture it all. Your Update statement is in there somewhere.


Thank you for all answers. I have found Linq To Sql Profiler to solve the problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消