Entity Framework 6.X实现记录执行的SQL功能
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功能的更多相关文章
- 【Entity Framework】disable automatic migration, 执行update-migration仍然会显示有automatic migration
本文涉及的相关问题,如果你的问题或需求有与下面所述相似之处,请阅读本文 [Entity Framework] disable automatic migration, 执行update-migrati ...
- 转:Entity FrameWork利用Database.SqlQuery<T>执行存储过程并返回参数
public IEnumerable<Statistic> GetStatistics(IEnumerable<Guid> itemIds) { var ctx = new D ...
- [转]Entity FrameWork利用Database.SqlQuery<T>执行存储过程并返回参数
本文转自:http://www.cnblogs.com/xchit/p/3334782.html 目前,EF对存储过程的支持并不完善.存在以下问题: EF不支持存储过程返回多表联合查询的 ...
- Entity FrameWork利用Database.SqlQuery<T>执行存储过程并返回参数
目前,EF对存储过程的支持并不完善.存在以下问题: EF不支持存储过程返回多表联合查询的结果集. EF仅支持返回返回某个表的全部字段,以便转换成对应的实体.无法支持返回部分字段的情况. 虽然可以正常导 ...
- MVC5 Entity Framework学习参加排序、筛选和排序功能
上一篇文章实现Student 基本的实体CRUD操作.本文将展示如何Students Index页添加排序.筛选和分页功能. 以下是排序完成时.经过筛选和分页功能截图,您可以在列标题点击排序. 1.为 ...
- EF 记录执行的sql语句
最近做了个中等的项目,数据不会很多,开发时间比较紧迫,所以用了EF的框架. 在使用过程中,发现有时候执行的结果不如预期,想看看执行的sql语句为何,遍查找资料,在网上找到了相关辅助类,拿来使用,部署到 ...
- Entity FrameWork 5 增删改查 & 直接调用sql语句 ?
#region 1.0 新增 -void Add() /// <summary> /// 1.0 新增 /// </summary> static void Add() { / ...
- Entity Framework 利用 Database.SqlQuery<T> 执行存储过程,并返回Output参数值
做个记录: var pCount = this._dataProvider.GetParameter(); pCount.ParameterName = "totalCount"; ...
- Entity Framework学习 - 5.DB First执行时提示model没有key
原因:自动生成的类中有关联主键,没有自动生成Key及Column 解决方法:在xxx.tt的66行左右修改为 var simpleProperties = typeMapper.GetSimplePr ...
随机推荐
- 数字和表达式(python)
>>>2+2 4 >>>1/2#(注:3.0版本之前是这样的,整数除法) >>>1.0/2.0 0.5 >>>1.0/2 0.5 ...
- Mysql 断电数据损毁恢复
error log: Database page corruption on disk or a failed 处理: /etc/my.cnf 设置 innodb_force_recovery = 6 ...
- linux文件 面试知识
1. 文件存储结构 Linux正统的文件系统(如ext2.ext3)中,一个文件由目录项.inode和数据块组成. 目录项:包括文件名和inode节点号. inode:又称文件索引节点, ...
- spark job运行参数优化
http://www.cnblogs.com/LBSer/p/4129481.html 一.问题 使用spark join两张表(5000w*500w)总是出错,报的异常显示是在shuffle阶段. ...
- rpm使用方法
查看rpm信息:rpm -q [软件的rpm名字]rpm -q下还有很多选项,具体功能如下:rpm -qa 列出所有已安装的RPM文件rpm -qa | grep [rp ...
- sql典例分析
1. 条件过滤 & Having 表结构 #tab_a #tab_b 表关系 tab_a.id = tab_b.relation_id 表数据 需求 查新把tab_a的ID对应的表tab_b的 ...
- SSH和SSL比较
一.SSH介绍 什么是SSH? 传统的网络服务程序,如:ftp.pop和telnet在本质上都是不安全的,因为它们在网络上用明文传送口令和数据, 别有用心的人非常容易就可以截 获这些口令和数据.而且, ...
- 功能------常用快捷键(在win10下)
功能------win10 常用快捷键 在进行学习,记录,编写代码时,需要用到一些功能,用鼠标浪费时间,可以使用快捷键来快速的处理.方便操作. 以下内容分为两类.快捷键以及触控板类(不能享用鼠标) 快 ...
- [POI 2014]RAJ-Rally
Description 题库链接 给定一个 \(N\) 个点 \(M\) 条边的有向无环图,每条边长度都是 \(1\).请找到一个点,使得删掉这个点后剩余的图中的最长路径最短. \(1\leq N\l ...
- angularjs 依赖注入原理与实现
在用angular依赖注入时,感觉很好用,他的出现是 为了“削减计算机程序的耦合问题” ,我怀着敬畏与好奇的心情,轻轻的走进了angular源码,看看他到底是怎么实现的,我也想写个这么牛逼的功能.于是 ...