Entity Framework在使用时,很多时间操纵的是Model,并没有写sql语句,有时候为了调试或优化等,又需要追踪Entity framework自动生成的sql(最好还能记录起来,方便出错时排查)

方式一:

通过System.Data.Entity.DataBase.Log属性指定一个无返回值的委托,来实现记录日志的功能

public partial class EFContext<T> : DbContext where T : class
{
public EFContext(): base("name=MyConnectionString")
{
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<EFContext<T>> (null); Database.Log = log => File.AppendAllText("ef.log",string.Format("{0}{1}{2}", DateTime.Now, Environment.NewLine, log)); modelBuilder.Configurations.Add(new MemberMap());
modelBuilder.Configurations.Add(new RoleMap());
base.OnModelCreating(modelBuilder);
} public DbSet<T> Table { get; set; } public IQueryable<T> GetList(Expression<Func<T,bool>> where)
{
return this.Table.Where(where);
}
}

其中:Database.Log = log => File.AppendAllText("ef.log",string.Format("{0}{1}{2}", DateTime.Now, Environment.NewLine, log));  设置写入日志

控制台代码:

EFContext<Member> efMemberContext = new EFContext<Member>();
var memberSet = efMemberContext.Set<Member>().Include("Role"); var memberList = memberSet.OrderBy(m => new { m.RoleId, m.Name });
foreach (Member item in memberList)
{
Console.WriteLine("{0},Role:{1}",item.Name,item.Role.Name);
}

运行程序后,打开ef.log文件,发现记录了日志

方式二:自定义一个类,继承于DbCommandInterceptor,重写下面几个方法

public class EFDbCommandInterceptor : DbCommandInterceptor
{
/// <summary>
/// 计时器
/// </summary>
public volatile Stopwatch watch = new Stopwatch(); public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
base.NonQueryExecuting(command, interceptionContext);
watch.Restart();
} public override void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
watch.Stop();
if (interceptionContext.Exception != null)
{
WriteLog(string.Format("Exception:{1} \r\n --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString()));
}
else
{
WriteLog(string.Format("\r\n执行时间:{0} 毫秒\r\n-->ScalarExecuted.Command:{1}\r\n", watch.ElapsedMilliseconds, command.CommandText));
}
base.NonQueryExecuted(command, interceptionContext);
} public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
base.ScalarExecuting(command, interceptionContext);
watch.Restart();
} public override void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
watch.Stop();
if (interceptionContext.Exception != null)
{
WriteLog(string.Format("Exception:{1} \r\n --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString()));
}
else
{
WriteLog(string.Format("\r\n执行时间:{0} 毫秒\r\n-->ScalarExecuted.Command:{1}\r\n", watch.ElapsedMilliseconds, command.CommandText));
}
base.ScalarExecuted(command, interceptionContext);
} public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
base.ReaderExecuting(command, interceptionContext);
watch.Restart();
} public override void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
watch.Stop();
if (interceptionContext.Exception != null)
{
WriteLog(string.Format("Exception:{1} \r\n --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString()));
}
else
{
WriteLog(string.Format("\r\n执行时间:{0} 毫秒\r\n-->ScalarExecuted.Command:{1}\r\n", watch.ElapsedMilliseconds, command.CommandText));
}
base.ReaderExecuted(command, interceptionContext);
}
/// <summary>
/// 记录日志
/// </summary>
/// <param name="msg">消息</param>
private void WriteLog(string msg)
{
//指定true表示追加
using (TextWriter writer = new StreamWriter("Db.log",true))
{
writer.WriteLine(msg);
}
}
}
public partial class EFContext<T> : DbContext where T : class
{
public EFContext(): base("name=MyConnectionString")
{
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<EFContext<T>> (null); //Database.Log = log => File.AppendAllText("ef.log",string.Format("{0}{1}{2}", DateTime.Now, Environment.NewLine, log)); DbInterception.Add(new EFDbCommandInterceptor()); modelBuilder.Configurations.Add(new MemberMap());
modelBuilder.Configurations.Add(new RoleMap());
base.OnModelCreating(modelBuilder);
} public DbSet<T> Table { get; set; } public IQueryable<T> GetList(Expression<Func<T,bool>> where)
{
return this.Table.Where(where);
}
}

其中DbInterception.Add(new EFDbCommandInterceptor());  设置日志记录

还是刚才的控制台代码,运行程序,打开Db.log

另外还有其它方法获取Entity Framework 执行的sql代码,比如SQL Server Profiler工具,不过这个不属于通过Entity Framework代码去配置,所以在此就不再赘述

Entity Framework 6.X实现记录执行的SQL功能的更多相关文章

  1. 【Entity Framework】disable automatic migration, 执行update-migration仍然会显示有automatic migration

    本文涉及的相关问题,如果你的问题或需求有与下面所述相似之处,请阅读本文 [Entity Framework] disable automatic migration, 执行update-migrati ...

  2. 转:Entity FrameWork利用Database.SqlQuery<T>执行存储过程并返回参数

    public IEnumerable<Statistic> GetStatistics(IEnumerable<Guid> itemIds) { var ctx = new D ...

  3. [转]Entity FrameWork利用Database.SqlQuery<T>执行存储过程并返回参数

    本文转自:http://www.cnblogs.com/xchit/p/3334782.html 目前,EF对存储过程的支持并不完善.存在以下问题:        EF不支持存储过程返回多表联合查询的 ...

  4. Entity FrameWork利用Database.SqlQuery<T>执行存储过程并返回参数

    目前,EF对存储过程的支持并不完善.存在以下问题: EF不支持存储过程返回多表联合查询的结果集. EF仅支持返回返回某个表的全部字段,以便转换成对应的实体.无法支持返回部分字段的情况. 虽然可以正常导 ...

  5. MVC5 Entity Framework学习参加排序、筛选和排序功能

    上一篇文章实现Student 基本的实体CRUD操作.本文将展示如何Students Index页添加排序.筛选和分页功能. 以下是排序完成时.经过筛选和分页功能截图,您可以在列标题点击排序. 1.为 ...

  6. EF 记录执行的sql语句

    最近做了个中等的项目,数据不会很多,开发时间比较紧迫,所以用了EF的框架. 在使用过程中,发现有时候执行的结果不如预期,想看看执行的sql语句为何,遍查找资料,在网上找到了相关辅助类,拿来使用,部署到 ...

  7. Entity FrameWork 5 增删改查 & 直接调用sql语句 ?

    #region 1.0 新增 -void Add() /// <summary> /// 1.0 新增 /// </summary> static void Add() { / ...

  8. Entity Framework 利用 Database.SqlQuery<T> 执行存储过程,并返回Output参数值

    做个记录: var pCount = this._dataProvider.GetParameter(); pCount.ParameterName = "totalCount"; ...

  9. Entity Framework学习 - 5.DB First执行时提示model没有key

    原因:自动生成的类中有关联主键,没有自动生成Key及Column 解决方法:在xxx.tt的66行左右修改为 var simpleProperties = typeMapper.GetSimplePr ...

随机推荐

  1. bug、兼容性、适配问题

    1.input   type=“number” 在火狐上限制长度会有问题: 1.maxlength 不管用 2.正则或js匹配限制长度后,给这个input赋值时候末尾三位(有可能是几位,我遇到的是三位 ...

  2. safari input默认样式

    在i标签下嵌套一个input标签  设置了 -webkit-apprarence:none: 设置了宽高,和padding:3px 结果placeholder显示不全 经排查 这时候的input默认有 ...

  3. 阿里云域名ssl证书导入aws负载均衡使用

    一 .原因 由于公司战略需求,需要将阿里云的服务器迁移到aws,在迁移过程中,我们需要使用的是aws的负载均衡,可以在EC2的控制台 负载平衡位找到负载均衡.根据业务需求我们使用的是应用程序负载均衡器 ...

  4. idea 错误: -source 1.6 中不支持 diamond 运算符的解决办法

    在取一段github代码时,发现说是支持jdk 7 ,但是使用MAVEN编译不过去. 报错信息为错误: -source 1.6 中不支持 diamond 运算符 我使用的环境是1.7  + intel ...

  5. WPF多路绑定

    WPF多路绑定 多路绑定实现对数据的计算,XAML:   引用资源所在位置 xmlns:cmlib="clr-namespace:CommonLib;assembly=CommonLib&q ...

  6. [codeup] 2046 八皇后

    题目描述 会下国际象棋的人都很清楚:皇后可以在横.竖.斜线上不限步数地吃掉其他棋子.如何将8个皇后放在棋盘上(有8 * 8个方格),使它们谁也不能被吃掉!这就是著名的八皇后问题. 对于某个满足要求的8 ...

  7. 网络爬虫(一):配置selenium、pycharm(windows平台)

    最近在学习爬虫的编写,使用selenium模块时候,遇到了很多坑,本blog的目的是总结一下遇到的坑和解决办法,以便后来人少走弯路! 以下介绍均以Python3.x为基准进行,基于windows平台的 ...

  8. springcloud-Feign基础使用

    声明式REST客户端:Feign Feign是一个声明式的Web服务客户端.它使得Web服务客户端的写入更加方便.具有可插拔注解支持,包括Feign注解和JAX-RS注解. Spring Cloud增 ...

  9. Angular的第一个组件

    创建组件 在vscode的命令窗口输入: ng generate component login --inline-template --inline-style 或者简写 ng g c login ...

  10. 番外篇 之 JS调用

     C#Winform调用JS 执行JS(Javascript)方法          课前知识储备:                                                1, ...