在编写手动 SQL 时,很容易估计查询返回的数据的大小和形状。我越来越发现使用 LINQ to SQL 查询很难做到这一点。有时我发现的数据比我预期的要多得多——这确实会减慢直接访问数据库的远程客户端的速度。
我希望能够运行查询,然后准确地知道通过网络返回了多少数据,并使用它来帮助我优化。
我已经使用 DataContext.Log 方法连接了一个日志,但这只能告诉我发送的 SQL,而不是接收到的数据。
有小费吗?
在编写手动 SQL 时,很容易估计查询返回的数据的大小和形状。我越来越发现使用 LINQ to SQL 查询很难做到这一点。有时我发现的数据比我预期的要多得多——这确实会减慢直接访问数据库的远程客户端的速度。
我希望能够运行查询,然后准确地知道通过网络返回了多少数据,并使用它来帮助我优化。
我已经使用 DataContext.Log 方法连接了一个日志,但这只能告诉我发送的 SQL,而不是接收到的数据。
有小费吗?
注意:如果您有现有的 DataContext,则需要将连接强制转换为 SqlConnection
((SqlConnection)dc.Connection).StatisticsEnabled = true;
然后检索统计信息:
((SqlConnection)dc.Connection).RetrieveStatistics()
我发现没有办法抓取DataContext的SqlConnection,所以我手动创建了SqlConnection:
SqlConnection sqlConnection = new SqlConnection("your_connection_string");
// enable statistics
cn.StatisticsEnabled = true;
// create your DataContext with the SqlConnection
NorthWindDataContext nwContext = new NorthWindDataContext(sqlConnection);
var products = from product in nwContext
where product.Category.CategoryName = "Beverages"
select product;
foreach (var product in products)
{
//do something with product
}
// retrieve statistics - for keys see http://msdn.microsoft.com/en-us/library/7h2ahss8(VS.80).aspx
string bytesSent = sqlConnection.RetrieveStatistics()["BytesSent"].ToString();
string bytesReceived = sqlConnection.RetrieveStatistics()["BytesReceived"].ToString();