Home > Database > Mysql Tutorial > How Can I Log the SQL Generated by DbContext.SaveChanges()?

How Can I Log the SQL Generated by DbContext.SaveChanges()?

Patricia Arquette
Release: 2025-01-03 21:57:40
Original
852 people have browsed it

How Can I Log the SQL Generated by DbContext.SaveChanges()?

Logging the Generated SQL from DbContext.SaveChanges() in Your Program

Question:

How can you capture and log the SQL statements generated by DbContext.SaveChanges()?

Answer:

In Entity Framework 6.0:

  1. Access the Database property of the DbContext instance.
  2. Set the Log property to Console.WriteLine, which will output the generated SQL statements to the console.
context.Database.Log = Console.WriteLine;
Copy after login

For Advanced Scenarios:

For more complex logging requirements, consider using an interceptor. Interceptors allow you to customize how the DbContext interacts with the database. By implementing a custom interceptor, you can log the generated SQL statements and perform other actions before or after executing commands.

The above is the detailed content of How Can I Log the SQL Generated by DbContext.SaveChanges()?. 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