entity framework6 – 如何在调用SaveChanges之前查看将为插入生成的SQL

在Entity Framework 6中,是否可以调用SaveChanges 之前查看将为插入执行的SQL?

using (var db = new StuffEntities()){ db.Things.Add(new Thing({...}); //can I get the SQL insert statement at this point? db.SaveChanges(); } 

我很熟悉如何在执行之前为查询生成生成的SQL,如下所示:

 var query = db.Thing.Where(x => x.ID == 9); Console.WriteLine(query.ToString()); //this prints the SQL select statement 

查询返回IQueryable ,而insert返回DbSet并在DbSet上调用ToString只打印标准对象名称。

另一个选择(如果我理解你的问题正确),将使用IDbCommandInterceptor实现,它似乎允许您在执行之前检查SQL命令(我对冲我的话,因为我自己没有使用它)。

像这样的东西:

 public class CommandInterceptor : IDbCommandInterceptor { public void NonQueryExecuting( DbCommand command, DbCommandInterceptionContext interceptionContext) { // do whatever with command.CommandText } } 

在上下文静态构造函数中使用EF中提供的DBInterception类注册它:

 static StuffEntities() { Database.SetInitializer(null); // or however you have it System.Data.Entity.Infrastructure.Interception.DbInterception.Add(new CommandInterceptor()); } 

EF6中最简单的方法要在不更改代码的情况下使查询始终方便,就是将其添加到DbContext中,然后在调试时在visual studio中检查输出窗口上的查询。

 protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.Log = (query)=> Debug.Write(query); } 

编辑

LINQPad也是调试Linq的一个很好的选择,也可以显示SQL查询。

没有等效的query.ToString() AFAIK。 您最终可以使用DbContext.Database.Log属性:

 db.Database.Log = s => { // You can put a breakpoint here and examine s with the TextVisualizer // Note that only some of the s values are SQL statements Debug.Print(s); }; db.SaveChanges(); 

使用拦截器详细信息请参阅此链接

将其添加到.config文件中