关于EF6的记录Sql语句 与 EntityFramework.Extend 的诟病
1、关于EF6的记录Sql语句,一个老生长谈的问题。 他生成的sql语句实在是烂,大家都这样说
2、EF6 更新删除不方便,没有批量操作。所以,有人出了EF6.Extend 大家用起来也很爽
基于以上两点,我也尝试着使用 EF6.Extend 。本以为可以很好的,很美好。没有想到我遇到了一个大问题。
我需要 通过程序记录 EF执行的Sql语句,当然也包括 EF6.Extend 执行的Sql语句。(不是通过SqlProfiler)
在网上查找,发现 了一篇文章,我就这样抄下来了。(太匆忙解决问题,忘记了哪一篇)
继承了 System.Data.Entity.Infrastructure.Interception.DbCommandInterceptor ,实现相关方法。 然后在Main方法(程序入口)进行添加 DbInterception.Add(new EFIntercepterLogging());
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Interception;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace EF_Sqlite
{
class EFIntercepterLogging : DbCommandInterceptor
{
private readonly Stopwatch _stopwatch = new Stopwatch();
public override void ScalarExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
base.ScalarExecuting(command, interceptionContext);
_stopwatch.Restart();
}
public override void ScalarExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
_stopwatch.Stop();
if (interceptionContext.Exception != null)
{
Trace.TraceError("Exception:{1} \r\n --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString());
}
else
{
string txt=string.Format("\r\n执行时间:{0} 毫秒\r\n-->ScalarExecuted.Command:{1}\r\n", _stopwatch.ElapsedMilliseconds, command.CommandText);
Console.WriteLine(txt);
Trace.TraceInformation(txt);
}
base.ScalarExecuted(command, interceptionContext);
}
public override void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
base.NonQueryExecuting(command, interceptionContext);
_stopwatch.Restart();
}
public override void NonQueryExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{ _stopwatch.Stop();
if (interceptionContext.Exception != null)
{
Trace.TraceError("Exception:{1} \r\n --> Error executing command:\r\n {0}", command.CommandText, interceptionContext.Exception.ToString());
}
else
{ string txt = string.Format("\r\n执行时间:{0} 毫秒\r\n-->ScalarExecuted.Command:{1}\r\n", _stopwatch.ElapsedMilliseconds, command.CommandText);
Console.WriteLine(txt);
Trace.TraceInformation(txt);
}
base.NonQueryExecuted(command, interceptionContext);
}
public override void ReaderExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
{
base.ReaderExecuting(command, interceptionContext);
_stopwatch.Restart();
}
public override void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
{
_stopwatch.Stop();
if (interceptionContext.Exception != null)
{
Trace.TraceError("Exception:{1} \r\n --> Error executing command:\r\n {0}", command.CommandText, interceptionContext.Exception.ToString());
}
else
{
string txt = string.Format("\r\n执行时间:{0} 毫秒\r\n-->ScalarExecuted.Command:{1}\r\n", _stopwatch.ElapsedMilliseconds, command.CommandText);
Console.WriteLine(txt);
Trace.TraceInformation(txt);
}
base.ReaderExecuted(command, interceptionContext);
} }
}
日志记录类完整代码
通过EF正常的操作是可以记录到SQL语句的,而通过EF.Extend执行的删除操作是无法获取sql的。我想,是不是我写错了,可网上根本没有关于EF.Extend 记录生成SQL的只言片语,可能大家都没有遇到这样的问题。
只能硬着头皮,翻源码。
经过翻看EF.Extend的源码,发现他是直接用Command执行的sql,再翻 EF的源码发现,EF是绕了很大一圈来执行的SQL
找到EF的这里,我明白了
public virtual int NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
{
Check.NotNull(command, "command");
Check.NotNull(interceptionContext, "interceptionContext"); return _internalDispatcher.Dispatch(
command,
(t, c) => t.ExecuteNonQuery(),
new DbCommandInterceptionContext<int>(interceptionContext),
(i, t, c) => i.NonQueryExecuting(t, c),
(i, t, c) => i.NonQueryExecuted(t, c));
}
EF的执行代码
而,EF.Extend的代码是这样写的
private int InternalDelete<TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery<TEntity> query)
where TEntity : class
#endif
{
DbConnection deleteConnection = null;
DbTransaction deleteTransaction = null;
DbCommand deleteCommand = null;
bool ownConnection = false;
bool ownTransaction = false; try
{
// get store connection and transaction
var store = GetStore(objectContext);
deleteConnection = store.Item1;
deleteTransaction = store.Item2; if (deleteConnection.State != ConnectionState.Open)
{
deleteConnection.Open();
ownConnection = true;
} if (deleteTransaction == null)
{
deleteTransaction = deleteConnection.BeginTransaction();
ownTransaction = true;
} deleteCommand = deleteConnection.CreateCommand();
deleteCommand.Transaction = deleteTransaction;
if (objectContext.CommandTimeout.HasValue)
deleteCommand.CommandTimeout = objectContext.CommandTimeout.Value; var innerSelect = GetSelectSql(query, entityMap, deleteCommand); var sqlBuilder = new StringBuilder(innerSelect.Length * ); sqlBuilder.Append("DELETE ");
sqlBuilder.Append(entityMap.TableName);
sqlBuilder.AppendLine(); sqlBuilder.AppendFormat("FROM {0} AS j0 INNER JOIN (", entityMap.TableName);
sqlBuilder.AppendLine();
sqlBuilder.AppendLine(innerSelect);
sqlBuilder.Append(") AS j1 ON ("); bool wroteKey = false;
foreach (var keyMap in entityMap.KeyMaps)
{
if (wroteKey)
sqlBuilder.Append(" AND "); sqlBuilder.AppendFormat("j0.[{0}] = j1.[{0}]", keyMap.ColumnName);
wroteKey = true;
}
sqlBuilder.Append(")"); deleteCommand.CommandText = sqlBuilder.ToString(); #if NET45
int result = async
? await deleteCommand.ExecuteNonQueryAsync().ConfigureAwait(false)
: deleteCommand.ExecuteNonQuery();
#else
int result = deleteCommand.ExecuteNonQuery();
#endif
// only commit if created transaction
if (ownTransaction)
deleteTransaction.Commit(); return result;
}
finally
{
if (deleteCommand != null)
deleteCommand.Dispose(); if (deleteTransaction != null && ownTransaction)
deleteTransaction.Dispose(); if (deleteConnection != null && ownConnection)
deleteConnection.Close();
}
}
EF.Extend的执行代码
经过分析,是这个道理,按照这个逻辑,EF.Extend没有按照EF的逻辑写,所以,他不能通过这种方式记录Sql。
恍然大悟后,我这样执行的Sql
System.Data.Common.DbConnection con = t.Database.Connection;
System.Data.Common.DbCommand command = con.CreateCommand();
con.Open();
command.CommandText = "delete from area where 1=2 and 4=9";
DbInterception.Dispatch.Command.NonQuery(command, new DbCommandInterceptionContext());
EF 自定义的SQL执行
就这样,我 通过统一的方式,获取到了我自己执行的Sql语句,和EF执行的Sql语句
本来是打算用EF.Extend的,看到这里,我决定不用了,有点杀鸡用牛刀。(其实,EF.Extend 不仅扩展了修改和删除的方法,还扩展了 EF没有的二级缓存,等等。如果只是用到修改删除的扩展方法,那可以放弃Extend了。)
关于EF6的记录Sql语句 与 EntityFramework.Extend 的诟病的更多相关文章
- ORACLE百万记录SQL语句优化技巧
1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引. 2.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索 ...
- MySQL 5.6 记录 SQL 语句与慢查询
环境: MySQL 如果需要记录 MySQL 的查询语句,需要在配置文件(Linux 下为 my.cnf,Windows 下为 my.ini)中添加配置: general_log = ON gener ...
- Ora中select某时间段记录sql语句
要查找某时间段的记录,例如查找2013-11-1到2013-11-30的记录. ' group by user_name, user_id 注意:SQL语句中含有sum累加函数,末尾要加group b ...
- EF6中执行Sql语句
EF中提供了两个方法,一个是执行查询的Sql语句SqlQuery,另外一个是执行非查询的语句ExecuteSqlCommand.SqlQuery有两种形式的,一种是泛型的,一种是非泛型的.比如我们要在 ...
- EF6.0 下sql语句自动生成的参数类型decimal(18,2)修改
很多时候我们需要对插入到数据库的数据的精度做一个控制,例如sql server下保留6位小数使用numeric(10,6) .而到c#里对应的数据类型就是decimal ,但是使用EF6.0的crea ...
- 用mybatis时log4j总是不记录sql语句
log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).log4j:WARN ...
- 记录sql语句的执行记录,用于分析
SET STATISTICS PROFILE ONSET STATISTICS IO ONSET STATISTICS TIME ONGO --这之间是要执行的脚本select * from [Use ...
- [转]在EntityFramework6中执行SQL语句
本文转自:http://www.cnblogs.com/wujingtao/p/5412329.html 在上一节中我介绍了如何使用EF6对数据库实现CRDU以及事务,我们没有写一句SQL就完成了所有 ...
- 在EntityFramework6中执行SQL语句
在EntityFramework6中执行SQL语句 在上一节中我介绍了如何使用EF6对数据库实现CRDU以及事务,我们没有写一句SQL就完成了所有操作.这一节我来介绍一下如何使用在EF6中执行SQL语 ...
随机推荐
- MongoDB 优化器MongoDB Database Profiler(12)
优化器profile 在MySQL 中,慢查询日志是经常作为我们优化数据库的依据,那在MongoDB 中是否有类似的功能呢?答案是肯定的,那就是MongoDB Database Profiler. 1 ...
- Datazen地图Chart自定义数据
此篇介绍如何将数据关联到Datazen地图图表.我们会将数据库中的数据映射到地图上. 首先查看下默认地图图表绑定的数据.以下是系统自带的美国地图数据,主要有两列,一列为地名,一列为度量数据.地图会根据 ...
- 【My Life】写在年末, 我的2013
[My Life]写在年末, 我的2013 SkySeraph Dec. 30 2013 Email:skyseraph00@163.com 好久没写博客了, 遗忘的历史,遗忘了自我... 岁月拾回 ...
- cout输出控制——位数和精度控制
刷到一道需要控制输出精度和位数的题目 刚开始以为单纯使用 iomanip 函数库里的 setprecision 就可以,但 OJ 给我判了答案错误,后来一想这样输出并不能限制位数只能限制有效位数. 比 ...
- yii2的分页和ajax分页
要想使用Yii分页类第一步:在控制器层加载分页类 use yii\data\Pagination;第二步: 使用model层查询数据,并用分分页,限制每页的显示条数$data = User::find ...
- 追踪记录每笔业务操作数据改变的利器——SQLCDC
对于大部分企业应用来用,有一个基本的功能必不可少,那就是Audit Trail或者Audit Log,中文翻译为追踪检查.审核检查或者审核记录.我们采用Audit Trail记录每一笔业务操作的基本信 ...
- 深入理解Javascript--闭包
原网站http://www.cnblogs.com/xiaoloulan/p/5980569.html 在了解闭包之前需要了解下作用域的工作原理作为基础,传送门. 闭包是一个老生常谈的问题,在面试中也 ...
- 切图时图片的选择:JPG、PNG、GIF的区别
目前网站图片的采用一共有流行三种,分别是JPG.PNG.GIF,然而很多人并不知道三者在选择的时候究竟应该选谁.虽然都可以存储图片,但是如果要发布到网上,就必须考虑速度.大小和失真程度的问题.如果你运 ...
- Shell scripts to Create a local dir base on the time.
#!/bin/bash DATETIME=`date +%Y%m%d%H%M%S` echo "datetime = $DATETIME" mkdir $DATETIME # cd ...
- 闲来无事,写个基于TCP协议的Socket通讯Demo
.Net Socket通讯可以使用Socket类,也可以使用 TcpClient. TcpListener 和 UdpClient类.我这里使用的是Socket类,Tcp协议. 程序很简单,一个命令行 ...