Database Command Logging:
In this section, you'll learn how to log commands & queries sent to the database by Entity Framework.
Prior to EF 6, we used the database tracing tool or third party tracing utility to trace database queries and commands Sen T by Entity Framework. Now, the EF 6 provides a simple mechanism to log everything this Entity Framework is doing. It logs all of the activity performed by EF using context.database.Log
You can attach any method of any class, which accepts one string parameter and returns void.
In the following example, we use Console.Write method to log EF activities:
using (varnew schooldbentities ()) { = console.write; var student = context. Students "Student1"). Firstordefault<student>(); " edited Name " ; Context. SaveChanges ();}
Output:
You can see in the output so it logs all the activities performed by EF, e.g. opening & closing connection, Executio N & Completion time and database queries & commands.
Context.Database.Log is a action<string> so, can attach any method which have one string parameter and void return type. For example:
Public classlogger{ Public Static voidLog (stringmessage) {Console.WriteLine ("EF Message: {0}", message); }}classef6demo{ Public Static voiddbcommandlogging () {using(varContext =Newschooldbentities ()) {context. Database.Log=Logger.Log; varStudent =context. Students. Where (S= = S.studentname = ="Student1"). Firstordefault<student>(); Student. Studentname="edited Name"; Context. SaveChanges (); } }}
Download DB First sample project for DB command logging demo.
Entity Framework 6.0 Tutorials (4): Database Command Logging