Log Queries executed by Entity Framework DbContext(实体框架 DbContext 执行的日志查询)
问题描述
我在 MVC 5 项目中使用 EF 6.0 和 LINQ.我想记录实体框架 DbContext 执行的所有 SQL 查询,以用于调试/性能测量.
I'm using EF 6.0 with LINQ in MVC 5 project. I want to log all the SQL queries executed by the Entity Framework DbContext for debugging/performance-measurement purpose.
在 Java/Hibernate 中,可以通过设置属性 hibernate.show_sql=true
来实现等效行为.实体框架中是否可能有类似的行为?
In Java/Hibernate, equivalent behavior can be achieved by setting the property hibernate.show_sql=true
. Is it possible to have a similar behavior in Entity Framework?
推荐答案
日志记录和MSDN 上的 Intercepting Database Operations 文章正是您想要的.
DbContext.Database.Log
属性可以设置为任何采用字符串的方法的委托.最常见的是通过将它设置为该 TextWriter 的Write"方法来与任何 TextWriter
一起使用.当前上下文生成的所有 SQL 都将记录到该编写器.例如,以下代码会将 SQL 记录到控制台:
The DbContext.Database.Log
property can be set to a delegate for any method that takes a string. Most commonly it is used with any TextWriter
by setting it to the "Write" method of that TextWriter. All SQL generated by the current context will be logged to that writer. For example, the following code will log SQL to the console:
using (var context = new BlogContext())
{
context.Database.Log = Console.Write;
// Your code here...
}
这篇关于实体框架 DbContext 执行的日志查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:实体框架 DbContext 执行的日志查询


基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01