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 ...
随机推荐
- OpenGL12-shader(GLSL)着色语言1(代码已上传)
OpenGL着色语言(GLSL――OpenGL Shading Language)是用来在OpenGL中着色编程的语言, 也即开发人员写的短小的自定义程序,他们是在图形卡的GPU (Graphic P ...
- Maven 学习笔记(二)
项目最近开始使用maven去管理项目啦,说真的对于maven是一窍不通啊,今天和同事在回家的路上聊天的时候同事说他去第一家公司面试的时候人家问他 maven 怎么打包,当时我就懵逼了,因为我也不知道啊 ...
- android学习-Toast的延迟时间
一般显示Toast都是一条语句够了 Toast.makeText(Context context, CharSequence text, int duration) Context是要显示Toast的 ...
- [笔记] Python 中JSON数据的读写
前言 JSON(JavaScript Object Notation,JavaScript对象表示法)是一种轻量级的数据交换语言 JSON是独立于语言的文本格式, JSON 数据格式与语言无关 JSO ...
- 获得Spring容器
1. WebApplicationContext wac = ContextLoader.getCurrentWebApplicationCon; 2. ClassPathXmlApplication ...
- java开发编译器:中间语言格式
阅读博客的朋友可以到我的网易云课堂中,通过视频的方式查看代码的调试和执行过程: http://study.163.com/course/courseMain.htm?courseId=10028300 ...
- I/O模式总结
进程读取数据时要经过两个阶段: 1.等待内核准备数据: 2.将内核缓冲区中的数据复制到进程缓冲区中. 一.阻塞IO 进程会阻塞在等待内核准备数据和数据从内核空间复制到用户空间这两个阶段. 二.非阻塞I ...
- [转]UTF-8 encoding support for the BCP utility and BULK INSERT Transact-SQL command in SQL Server 2014 SP2
本文转自:https://support.microsoft.com/en-us/help/3136780/utf-8-encoding-support-for-the-bcp-utility-and ...
- C#比较两个字符串的相似度【转】
原文地址:http://www.2cto.com/kf/201202/121170.html 我们在做数据系统的时候,经常会用到模糊搜索,但是,数据库提供的模糊搜索并不具备按照相关度进行排序的功能. ...
- ASP.NET MVC 学习笔记-4.ASP.NET MVC中Ajax的应用
Ajax的全名为:Asynchronous Javascript And XML(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术.Ajax技术首先向Web服务器发送 ...