获取linq的sql语句(Get the SQL statement of LINQ).doc
文本预览下载声明
获取linq的sql语句(Get the SQL statement of LINQ)
Linq facilitates our operation of the database and operates the database directly with the syntax of C#. But Linq also hides the actual execution of SQL statements. Encapsulation is good, but sometimes you have to understand Linqs specific operations on the database. For example, you can only optimize the database or query statement by looking at the actual SQL statement, and its frustrating to not see SQL at debug time.
There are several ways to dig out the Sql statements used in the operation:
1. Get the SqlCommand object corresponding to Query:
In the development process, we can obtain the corresponding Sql Command object through Query. Please see the following code:
AdventureWorksDataContext DB = new, AdventureWorksDataContext ();
Var products = from, P, in, db.Products
Where p.ProductID = = 3
Select, new, {p.ProductID, p.Name};
Foreach (VaR, P, in, products)
{
Console.WriteLine (P);
}
DbCommand CMD = db.GetCommand (products);
Console.WriteLine (-);
Console.WriteLine (Command Text: \n{0}, cmd.CommandText);
Console.WriteLine (-);
Console.WriteLine (Command Type: \n{0}, cmd.CommandType);
Console.WriteLine (-);
Console.WriteLine (Command Parameters:);
Foreach (DbParameter, P, in, cmd.Parameters)
{
Console.WriteLine ({0}: {1}, p.ParameterName, p.Value);
}
Console.ReadLine ();
The output is as follows:
Command Text:
SELECT, [t0].[ProductID], [t0].[Name]
FROM [Production].[Product] AS [t0]
WHERE [t0].[ProductID] = @p0
-
Command Type:
Text
-
Command Parameters:
@p0: 3
As you can see, both the Sql statement and the arguments are printed out. In fact, since weve got the full SqlCommand object, we can get more information than just these.
2, the use of LINQ to SQL Debug Visualizer:
Using LINQ to SQL Debug Visiualizer, we can intuitively obtain the Sql statements and parameters corresponding to Query without having to obtain the SqlCommand object and print information when debugging the program. For specific use, see this blog po
显示全部