有没有办法在 C# 代码中获取两点之间的所有数据 (Linq-to-sql)

Is there any way to get all data retrieved between two points in C# code (Linq-to-sql)

我的场景如下: 我在一个用 C# Asp.Net 开发的系统中工作(一个大的、巨大的、无论如何都会发展的系统)。我正在尝试开始创建一些单元测试以开始重构(相信,它需要重构(有一些控制器有 10k、12k 行)。 问题是这个系统中的很多东西都与数据库有关(并且系统与数据库紧密耦合)。数据库上下文在很多代码片段中实例化,而不是注入。 所以,我现在的观点是将一些数据模拟到本地 MDB 文件中以重构代码并创建将拥有自己的 MDB 的单元测试(具有所有数据库结构,但仅包含他将使用的数据)。

我在想什么?类似的东西:

[TestMethod()]
public void AnyTest()
{
    var dbLogger = new DbLogger(); //this class is not created, it's just an example.
    dbLogger.Start();

     WorstWrittenMethodEver(); //this method will call any other methods insides, 
                               //a couple of then 
                               //and I really don't know the order and the
                               //complexity (much times very high), and this will probably
                               //instantiate the DataContext a lot of times and do
                               //a lot of data retrieval.

    db.StopLog();
    Console.WriteLine(db.DataRetrieved); //And in this line I will print all the tables 
   //and data retrieved between this two points.
}

之后,我将获取该数据,模拟到一个 MDB 文件中,并重构上面的单元测试以获得真正的单元测试。

有办法吗?

看来这不是一件容易的事。而且我认为您应该使用一些流行且经过测试的库或工具。我的建议是使用MiniProfiler。它允许捕获所有 SQL 查询(还包括对 LinqToSql 的支持)。它有很好的 UI 和 API 可以在您的代码中进行交互。实际上要获取所有 SQL 查询数据,您可以使用以下方法:

MiniProfiler.Current.GetSqlTimings();