The Logging and Intercepting Database Operations article from MSDN describes the use of the Log property for logging SQL including SQL generated by the SaveChanges() method for EF6+.
I am trying to intercept all generated sql from my Context class which inherits from DbContext. The interception works fine for everything except the SQL which is generated by the SaveChanges() method.
Is DbContext.Database.Log the correct property to use for logging this?
Is there another way to log the SQL generated by the SaveChanges() method?
using (Context c = new Context())
{
//setup logging to debugger
c.Database.Log = s => Debug.WriteLine(s);
//generate query
var query = c.SomeTable.Where(x => x.Abc == "A" && x.Zyx == "Z");
//enumerate query - generated SQL is logged to debugger correctly
var items = query.ToList();
//modify entities
items.ForEach(t => t.Timestamp = DateTime.Now);
//get number of changed entities: Outputs "Number of Changed Entities: 3"
var changedEntries = c.ChangeTracker.Entries().Where(e => e.State != EntityState.Unchanged);
Debug.WriteLine("Number of Changed Entities: {0}", changedEntries.Count());
//save changes - generated SQL is NOT logged to debugger
c.SaveChanges();
}
UPDATE
I found out where the problem was. I was using a Context which is derived from DBContext, and which had overridden the SaveChanges() method. Inside the overridden method, it was re-routing the DbContext.Database.Log to a string builder, instead of the debugger.
The Context, which derives from DbContext, was overriding the SaveChanges() method. Inside the overridden method, it was re-routing the DbContext.Database.Log to a string builder, instead of the debugger.