0

Lets say I have the code

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();

When SaveChanges() is called how can I see in code the SQL statement that is generated?

Tono Nam
  • 34,064
  • 78
  • 298
  • 470

1 Answers1

2

If this is LINQ-to-SQL, then you can attach a TextWriter to Db.Log: then everything you do via Db will be recorded in there. Alternatively, you could use a tool like mini-profiler and just give MyEntities a wrapped connection, i.e.

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()))
{
    ...
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900