Introduction
Entity Framework Logging features were introduced in Entity Framework 6.This feature gives us the opportunity to log every executing query or command sent to the database. This is the best or easiest way to track what's happening with the database. Before this, we had used the SQL Profiler to see what EF request is running and which query has executed and the result. So, now we have this feature integrated with EF6. The important use of this feature is to track of unexpected error/results and to find the performance issues by looking at the logged report, it can track by time, query result and more. We can also see how the Entity Framework translates the Linq query to SQL query.It logs all the activity performed by EF using context.database.Log. Here, you can attach any method of any class, which accepts one string parameter and returns void.
Logging
The DbContext.Database.Log help us to record or track the pieces of information about database operation. Here we will record all information to file.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.IO;
- namespace EFLogging {
- class Program {
- private static CSharpCornerEntities context = new CSharpCornerEntities();
- static void Main(string[] args) {
- context.Database.Log = logInfo => FileLogger.Log(logInfo);
- InsertEmployeeRecord();
- UpdateEmployeeRecord(10024);
- context.Database.Log = Console.Write;
- }
- private static void UpdateEmployeeRecord(long employeeID) {
-
- var empData = (from employee in context.Employees where employee.ID == employeeID select employee).FirstOrDefault();
-
-
- empData.Location = "UK";
- context.Entry(empData).State = System.Data.Entity.EntityState.Modified;
- context.SaveChanges();
- }
- private static void InsertEmployeeRecord() {
- context.Employees.Add(new Employee {
- Designation = "Software Engineer ", Location = "Chennai", Name = "DummyRecord"
- });
- context.SaveChanges();
- }
- }
- public class FileLogger {
- public static void Log(string logInfo) {
- File.AppendAllText(@ "C:\Users\SMKG\Desktop\Logger.txt", logInfo);
- }
- }
- }
Look at the above code, I mentioned The DbContext.Database.Log property can be set to a delegate for any method that takes a string. Here,I created FileLogger class and Log method to record the respective database information using DbContext.Database.Log property. All SQL generated by the current context will be logged to that FileLogger class using Log method.
Once I executed the code above, you will see extra log information in stored file, now let us open the respective file
I hope it's helpful.