获取Linq to SQL中LINQ命令发出的SQL查询 [英] Get the SQL query issued by a LINQ command in Linq to SQL
问题描述
我抓取将由LINQ to SQL命令发出的SQL,并将其存储在我的C#代码中的字符串中.我不想将其发送到控制台,也不想在SQL Studio或LinqPad中对其进行单独分析.我想要该字符串,以便我的程序可以使用该字符串执行所需的操作. (实际上,我会将其发送到log4net,但这是偶然的).
I grab the SQL that will be issued by a LINQ to SQL command and store it in a string in my C# code. I do not want to have it sent to console out, not do I want to analyze it separately in SQL Studio or LinqPad. I want to have that string so that my program can do what it wants with the string. (In reality, I will send it to log4net, but that's incidental).
有人知道怎么得到这个吗?我知道在开始遍历迭代器之前,实际上不会将SQL发布到数据库,但是我希望也许有一种方法可以预先获取SQL.
Does anyone know how to get this? I know that the SQL is not actually issued to the database until you start walking through the iterators, but I am hoping that perhaps there is a way to get the SQL beforehand.
推荐答案
If you are using the Entity Framework you can use the ToTraceString()
method on an ObjectQuery like this:
ObjectQuery<Product> productQuery =
from p in context.Products
select p;
string sql = productQuery.ToTraceString();
如果您使用的是Linq to Sql,则说明DataContext具有日志属性,可用于获取Sql输出.
If you are using Linq to Sql, you're DataContext has a Log property that you can use to get the Sql output.
StringBuilder logBuilder = new StringBuilder();
db.Log = new StringWriter(logBuilder);
var custQuery =
(from cust in db.Customers
where cust.City == "London"
select cust).ToList();
string sql = logBuilder.ToString();
这篇关于获取Linq to SQL中LINQ命令发出的SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!