Retrieve LINQ to sql statement (IQueryable) WITH parameters

前端 未结 4 2050
广开言路
广开言路 2021-02-01 14:16

I\'m trying to figure out if there\'s a way to retrieve the (full) sql statement that gets executed on the database server.
I found something already, but it does not exactl

相关标签:
4条回答
  • 2021-02-01 14:47
    (SqlCommand)dataContext.GetCommand(query)
    

    will give you access to Parameters collection.

    0 讨论(0)
  • 2021-02-01 14:49

    You can also see the generated sql query if you have an instance of IQueryable<T> and call the .ToString() method.
    For Example:

    var db = new DbContext();
    IQueryable<Blog> query = db.Blog.Where(tt=> tt.Id > 100).OrderByDescending(tt=>tt.Id);
    var sqlString = query.ToString();
    Console.WriteLine(sqlString);
    

    This will generate an output of:

    SELECT [Extent1].[Id] AS [Id], 
    [Extent1].[Title] AS [Title], 
    [Extent1].[Author] AS [Author], 
    [Extent1].[Text] AS [Text], 
    [Extent1].[CreatedAt] AS [CreatedAt], 
    [Extent1].[UpdatedAt] AS [UpdatedAt]
    FROM [dbo].[Blogs] AS [Extent1]
    WHERE [Extent1].[Id] > 100
    ORDER BY [Extent1].[Id] DESC
    
    0 讨论(0)
  • I'm using Datacontext.Log property to get the generated SQL Statement (it includes the statement text, and parameters).

    Just set YourDataContext.Log = SomeTextWriter.

    It can be written to a file (Log = new StreamWriter(@"c:\temp\linq.log")) or to debug window, see this post

    0 讨论(0)
  • 2021-02-01 15:05

    Once you get the Command you can print the CommandText and then loop through the Parameters collection and print all the individual parameters.

    Also there is the linq-to-sql debug visualizer which does the same in debug mode.

    A really nice tool to view the queries as they are happening is the Linq-to-sql profiler

    0 讨论(0)
提交回复
热议问题