Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4 - Get generated SQL for Updates/Inserts

With EF4, is it possible to get the generated SQL for Updates/Inserts rather than executing it... just like you can view the query SQL before it runs.

The reason is, I have a set of helper functions that execute SQL commands. For instance...

Decrement<Category>("ProductCount", categoryID);
SetNull<Product>("CategoryID", productID);

Which generates...

UPDATE Categories 
SET ProductCount = ProductCount - 1 
WHERE CategoryID = @CategoryID; 

UPDATE Products 
SET CategoryID = NULL 
WHERE CategoryID = @ProductID;

I usually run several commands per operation, so with each helper function call, the SQL is generated and stored. When I call SaveChanges(), all of the commands are run at ONE time.

The only problem is that EF runs its commands separately behind the scenes, then I run the others right afterward. It would be ideal to run everything as one single command.

like image 272
Sterling Nichols Avatar asked Feb 08 '11 16:02

Sterling Nichols


People also ask

How can I see the SQL statement generated by Entity Framework?

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.

How can I see SQL query generated by LINQ in Visual Studio?

Images ... select img; string sql = q. ToString(); sql will contain the sql select query. If you're debugging locally and using SQL Server, run the SQL Profiler.

How do I get an ID after inserting EF core?

EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. The above example will execute the following SQL in the database. WHERE @@ROWCOUNT = 1 AND [StudentID] = scope_identity();


1 Answers

You can get it at design time with Sql Profiler, but I think you're meaning that you want it at run-time. Here's an example I found on how to do that:

public static void WriteGeneratedSql(EntityCommand cmd)
{
     cmd.Prepare();

     IServiceProvider isp = (IServiceProvider)EntityProviderFactory.Instance;

     DbProviderServices mps = (DbProviderServices)isp.GetService(typeof(DbProviderServices));

     EntityCommandDefinition definition = (EntityCommandDefinition)mps.CreateCommandDefinition(cmd);

     int commandId = 1;

     foreach (string commandText in definition.MappedCommands)
     {
          Console.WriteLine("Generated Command {0}:", commandId);
          commandId++;
          Console.WriteLine(commandText);
     }
}

Found here.

like image 108
Chris B. Behrens Avatar answered Oct 20 '22 04:10

Chris B. Behrens