编写手动 SQL 时,很容易估计查询返回的数据的大小和形状。我越来越发现使用 LINQ to SQL 查询很难做到这一点。有时我发现数据比我预期的要多——这确实会减慢直接访问数据库的远程客户端的速度。

我希望能够运行查询,然后准确地知道通过网络返回了多少数据,并使用它来帮助我优化。

我已经使用 DataContext.Log 方法连接了一个日志,但这只能指示发送的 SQL,而不指示接收的数据。

有小费吗?

有帮助吗?

解决方案

看起来您可以获取 DataContext 的 SqlConnection 并打开统计信息。

统计数据之一是“返回的字节数”。

MSDN 参考链接

其他提示

笔记:如果您有现有的 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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top