如何确定从LINQ到SQL的结果集的大小(以字节为单位)

时间:2020-03-06 14:23:11  来源:igfitidea点击:

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

我希望能够运行一个查询,然后准确说明通过网络返回的数据量,并以此来帮助我进行优化。

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

有小费吗?

解决方案

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

统计信息之一是"返回的字节数"。

MSDN参考链接

我发现没有办法获取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();

注意:如果我们有现有的DataContext,则需要将连接强制转换为SqlConnection

((SqlConnection)dc.Connection).StatisticsEnabled = true;

然后使用以下命令检索统计信息:

((SqlConnection)dc.Connection).RetrieveStatistics()