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.
To view the SQL that will be generated, simply call ToTraceString() . You can add it into your watch window and set a breakpoint to see what the query would be at any given point for any LINQ query. You can attach a tracer to your SQL server of choice, which will show you the final query in all its gory detail.
If we want to create a data, we're going to use the SQL keyword, “Insert”. The general format is the INSERT INTO SQL statement followed by a table name, then the list of columns, and then the values that you want to use the SQL insert statement to add data into those columns.
var q = from img in context. Images ... select img; string sql = q. ToString(); sql will contain the sql select query.
You can get same generated SQL query manually by calling ToString: string sql = committeeMember. ToString(); This overridden method internally calls ObjectQuery.
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()); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With