简体   繁体   中英

Entity Framework 6 - How can I view the SQL that will be generated for an insert before calling SaveChanges

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();
}

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

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

The easiest way in EF6 To have the query always handy, without changing code is to add this to your DbContext and then just check the query on the output window in visual studio, while debugging.

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

EDIT

LINQPad is also a good option to debug Linq with and can also show the SQL queries.

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).

Something like this:

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

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());
}

There is no equivalent of the query.ToString() AFAIK. You can eventually use DbContext.Database.Log property:

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();

use Interceptors for detail see this link

add this in to .config file

<interceptors> 
  <interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework"> 
    <parameters> 
      <parameter value="C:\Temp\LogOutput.txt"/> 
    </parameters> 
  </interceptor> 
</interceptors>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM