How to Log Generated SQL from DbContext.SaveChanges()
In Entity Framework (EF), you can easily log the SQL statements generated by your DbContext.SaveChanges() method. Here's how:
Using Database.Log Property:
In EF 6.0 and later, the Database class has an Action
context.Database.Log = Console.WriteLine;
Using Interceptors:
If you need more advanced logging capabilities, you can use an interceptor. An interceptor is a class that inherits from DbInterceptor and overrides its various methods. One such method is OnNonQueryExecuted, which is called whenever a non-query statement is executed (such as SaveChanges()).
In the OnNonQueryExecuted method, you can access the SQL statement that was executed and log it to a file, database, or any other location.
Example Code:
Here's an example of an interceptor that logs the SQL statements to a file:
public class SqlLoggerInterceptor : DbInterceptor { private readonly TextWriter _logWriter; public SqlLoggerInterceptor(TextWriter logWriter) { _logWriter = logWriter; } public override void OnNonQueryExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) { _logWriter.WriteLine(command.CommandText); } }
You can register the interceptor like this:
Database.SetInitializer<MyContext>(null); Database.AddInterceptor(new SqlLoggerInterceptor(File.AppendText("log.txt")));
The above is the detailed content of How to Log SQL Statements Generated by DbContext.SaveChanges() in Entity Framework?. For more information, please follow other related articles on the PHP Chinese website!