关于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语 ...
随机推荐
- JavaScript call
<script> function dog() { this.sound = "wangwang~"; this.shout = function () { alert ...
- java的布尔运算符和位运算符
1.布尔运算符 && 逻辑与: || 逻辑或: != 不等于: 三元操作符:?: :表达式为 condition?expression1:expression2(当条件为真时 ...
- 进击的Python【第二十章】
1.Django请求的生命周期 路由系统 -> 试图函数(获取模板+数据=>渲染) -> 字符串返回给用户 2.路由系统 /index/ -> 函数或类.as_view() / ...
- z-stack组网过程
z-stack组网分:协调器建立网络.路由器和终端加入网络 暂时只记录第一次上电建立网络的过程,至于开启NV_RESTORE后,恢复原有的网络则暂时不分析. 一.协调器建立网络: 1.ZDO层的ZDA ...
- log4j使用--http://www.cnblogs.com/eflylab/archive/2007/01/11/618001.html
package log4jTest.com; import java.io.FileReader; import org.apache.log4j.BasicConfigurator; import ...
- 简述HTML DOM及其节点分类
在JavaScript中,document这个对象大家一定很熟悉,哪怕是刚刚开始学习的新人,也会很快接触到这个对象.而document对象不仅仅是一个普通的JavaScript内置对象,它还是一个巨大 ...
- 线段树 - ZYB's Premutation
ZYB has a premutation P,but he only remeber the reverse log of each prefix of the premutation,now he ...
- [RxJava^Android]项目经验分享 --- 异常方法处理
简单介绍一下背景,最近RxJava很火,我也看来学习一下,计划在项目的独立模块中使用它.使用过程中遇到很多问题,在这里记录分享一下.可能有使用不当的地方,大家多多包涵.对于RxJava的基本概念和功能 ...
- Agile
I think Agile development methodologies is something we get from our practice. It can be just acknow ...
- WPF-开机自启
#region 开机自启 /// <summary> /// 开机自启创建 /// </summary> /// <param name="exeName&qu ...