ADO.NET在提交更改之前查看将发送到SQL Server的查询

时间:2014-02-21 16:15:57

标签: c# linq linq-to-sql ado.net

让我说我有代码

var Db = new MyEntities();

Random r = new Random();

// select a random customer out of the first 5
var customer = Db.Customers.OrderBy(c=>c.Id).Skip(r.Next(0, 5)).Take(1); 

foreach (var c in customer)
{
    c.WonPrice = true;
}


// How can I see here before saving the changes in order to see
// the query that will be sent to SQL server?
Db.SaveChanges();

当调用SaveChanges()时,如何在代码中看到生成的SQL语句?

1 个答案:

答案 0 :(得分:2)

如果这是LINQ-to-SQL,那么您可以将TextWriter附加到Db.Log:然后您通过Db执行的所有操作都会记录在那里。或者,您可以使用mini-profiler之类的工具,只需给MyEntities一个包裹的连接,即

public static DbConnection GetOpenConnection()
{
    // A SqlConnection, SqliteConnection ... or whatever
    var cnn = CreateRealConnection();

    // wrap the connection with a profiling connection that tracks timings 
    return new StackExchange.Profiling.Data.ProfiledDbConnection(cnn,
                                                MiniProfiler.Current);
}

...
using(var Db = new MyEntities(GetOpenConnection()))
{
    ...
}