开发者

Linq to Entities: see the resulting query (context.Log = Console.Out)

开发者 https://www.devze.com 2023-02-09 22:07 出处:网络
I just realized if your C# application use LINQ-TO-SQL classes to interface with the database, you can your query like this

I just realized if your C# application use LINQ-TO-SQL classes to interface with the database, you can your query like this

        using (DatabaseContext context = new 开发者_运维知识库DatabaseContext())
        {
            context.Log = Console.Out;
            var query = from Person p in context.People
                        where person.Name == "john"
                        select p;                                
            Console.WriteLine(query.Name);
        }

What is the equivalent in LINQ-TO-ENTITY (is this another name for ADO.NET?) for

context.Log = Console.Out

Or there is another way to see your actual SQL query to the database?


I always use SQL Profiler if you have MS SQL Server. What DBMS is this for? LINQ 2 Entities supports multiple DB types.

This also works...

var cust = (from c in context.Customers select c);

string sql = ((ObjectQuery)cust).ToTraceString();

From MSDN forums


Using EntityFrame 6 it is possible to just to a ToString() on your query at least when using MySQL

var cust = (from c in context.Customers select c);
string sql = cust.ToString();

As Greg in the comments notes, this gives you the parameterized query, so you will need to add in the values you want to use.


You can trace your SQL when using Linq2Entities https://stackoverflow.com/questions/137712/sql-tracing-linq-to-entities

You may also want to look at this tool Huagati Query Profiler


I believe the Tabular Data Stream (TDS) protocol used by Microsoft SQL Server sends commands and responses in plain text by default so unless you encrypt the connection between your SQL Server and the client, you should be able to view both the request and response with a comprehensive packet sniffer.

It will take some work but using a packet sniffer in this manner should allow you to see what T-SQL your LINQ is getting translated to.

Side Notes:

  1. I recommend that you encrypt all communications between your client and SQL server unless both the client and server reside on the same machine and you are doing development testing.
  2. If you can't risk using a decyrpted connection for testing purposes, your packet sniffer may have a plugin that will allow you to decrypt encrypted traffic, but I am not sure if there are any risks in using such a decryption plugin.


EF doesn't have a direct parallel to the stream based loging that LINQ to SQL uses. There are a number of profiling options available for a variety of costs. I've discussed some of these options at http://www.thinqlinq.com/Post.aspx/Title/LINQ-to-Database-Performance-hints. You can find a listing of these profilers and other LINQ tools at http://www.thinqlinq.com/Post.aspx/Title/linq-tools.

0

精彩评论

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

关注公众号