Database Reference
In-Depth Information
{
Console.WriteLine("{0} gave {1}", donor.DonorName,
donor.Amount.ToString("C"));
}
}
Console.WriteLine("Press any key to close...");
Console.ReadLine();
}
}
public partial class EFRecipesEntities
{
public override int SaveChanges()
{
this.Database.Connection.StateChange += (s, e) =>
{
var conn = (DbConnection)s;
Console.WriteLine("{0}: Database: {1}, State: {2}, was: {3}",
DateTime.Now.ToShortTimeString(), conn.Database,
e.CurrentState, e.OriginalState);
};
return base.SaveChanges();
}
}
Following is the output from the code in Listing 12-3:
About to SaveChanges()
09:56 : Database: EFRecipes, State: Open, was: Closed
09:56: Database: EFRecipes, State: Closed, was: Open
Donations over $300
Robert Byrd gave $350.00
Kim Kerns gave $750.00
How It Works
To wire in the handler for the StateChange event, we implement the override SaveChanges() method.
Our event handler receives two parameters: the sender of the event and a StateChangeEventArgs . This second
parameter provides access to the CurrentState of the connection and the OriginalState of the connection. We create a
log entry indicating both of these states as well as the time of the event and the associated database.
If you are paying particularly close attention to the order of the log entries, you will notice that, in the second
using block, the connection to the database occurs during the execution of the query in the foreach loop, and
not when the query is constructed. This demonstrates the important concept that queries are executed only when
explicitly required. In our case, this execution occurs during the iteration.
 
Search WWH ::




Custom Search