2

I know there is a way to see SQL that will be executed when querying for data from a database. For example, when query is created I can use query.ToQueryString() (based on this answer from SO):

var query = _context.Widgets.Where(w => w.IsReal && w.Id == 42);  
var sql = query.ToQueryString();

But is there a way to see SQL that will be executed when SaveChanges() is called without actually executing SaveChanges()?

Code example that gets data from db and updates one field:

    var context = new AppContext();
    var author = context.Authors
                        .Include(a => a.Books)
                        .FirstOrDefault(a => a.AuthorId == 1);

    // update some property
    author.Books[0].BasePrice += 2;

   // here I want to see SQL that will be generated to 
   // update the database when I call context.SaveChanges()
   var sql = ...?
mlst
  • 2,688
  • 7
  • 27
  • 57
  • 1
    I think this is what you need - https://eamonkeane.dev/3-ways-to-view-sql-generated-by-entity-framework-core-5/ – dimitar.d Feb 11 '23 at 15:58
  • 3
    I doubt it. I'm pretty sure that while saving changes, EF generates each command "just in time". Because not doing that would possibly require huge amounts of memory and also because often commands need generated identity values from previous commands. You could intercept a command, log it and replace it by an empty string, but EF would immediately error out because it doesn't return the expected number of affected rows. I.e. you could do this with one, and only one, command. But why do you want that? – Gert Arnold Feb 11 '23 at 21:54

0 Answers0