实体框架6 - 如何在调用SaveChanges之前查看将为插入生成的SQL [英] Entity Framework 6 - How can I view the SQL that will be generated for an insert before calling SaveChanges

查看:85
本文介绍了实体框架6 - 如何在调用SaveChanges之前查看将为插入生成的SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实体框架6中,是否可以在调用SaveChanges之前查看将在插入 之前执行的SQL?

In Entity Framework 6, is it possible to view the SQL that will be executed for an insert before calling SaveChanges?

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

我熟悉如何在执行前如何获取生成的SQL for 查询

I'm familiar with how to get the generated SQL for a query before execution like so:

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

查询返回一个IQueryable&而一个插入返回一个DbSet,并且在DbSet上调用ToString只是打印标准对象名。

The query returns an IQueryable<> whereas an insert returns a DbSet and calling ToString on a DbSet just prints the standard object name.

推荐答案

另一个选项您的问题正确),将使用 IDbCommandInterceptor 实现,这似乎允许您先检查SQL命令他们被处决(我对我的话,因为我没有使用这个自己)。

Another option (if I understand your question correctly), would be to use an IDbCommandInterceptor implementation, which seemingly allows you to inspect SQL commands before they are executed (I hedge my words as I have not used this myself).

这样的东西:

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

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

Register it using the DBInterception class available in EF in your context static constructor:

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

这篇关于实体框架6 - 如何在调用SaveChanges之前查看将为插入生成的SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆