【问题标题】:ADO.NET see query that will be sent to SQL server before submitting changesADO.NET 在提交更改之前查看将发送到 SQL 服务器的查询
【发布时间】:2014-02-22 00:21:48
【问题描述】:

假设我有代码

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 语句?

【问题讨论】:

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


【解决方案1】:

如果这是 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()))
{
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多