Home > Database > Mysql Tutorial > How to Log SQL Statements Generated by DbContext.SaveChanges() in Entity Framework?

How to Log SQL Statements Generated by DbContext.SaveChanges() in Entity Framework?

Patricia Arquette
Release: 2025-01-04 16:23:41
Original
782 people have browsed it

How to Log SQL Statements Generated by DbContext.SaveChanges() in Entity Framework?

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 property called Log. By setting this property to a function that writes to the console, you can log the generated SQL statements.

context.Database.Log = Console.WriteLine;
Copy after login

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);
    }
}
Copy after login

You can register the interceptor like this:

Database.SetInitializer<MyContext>(null);
Database.AddInterceptor(new SqlLoggerInterceptor(File.AppendText("log.txt")));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template