1

I need the SQL generated for a query.

Since EF Core 5, we have IQueryable.ToQueryString() which provides the query itself without parameters.

The best I could find is this, which extracts parameters from the query using reflection. It works for all database providers. However it is for pre-Core EF.

How can I get the query AND parameters - either in the query itself, or as an array of objects like in the linked question? (Using reflection is ok, unless there's a better way.)

lonix
  • 14,255
  • 23
  • 85
  • 176
  • 1
    In case it's important, I'm using both the sqlite ad posgtres providers. But I'm hoping for a db-independent solution. – lonix Apr 03 '22 at 02:22
  • see https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/simple-logging – jazb Apr 03 '22 at 02:53
  • the doco for ef is top notch – jazb Apr 03 '22 at 03:06
  • 1
    @Jazb Thanks. I actually did try that, but the parameters are logged separately - so it's not useful during runtime. You can actually see an example [here](https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/simple-logging#message-contents-and-formatting), if there are parameters they are included the bit that says `Parameters=[...]`. Also, this is useful for diagnostics "after the fact", but what I'm after is to determine the query (e.g. `ToQueryString()`) during runtime. – lonix Apr 03 '22 at 03:08
  • What are you trying to implement? Executing queries via remote server? – Svyatoslav Danyliv Apr 03 '22 at 08:07
  • It's complicated :) for our internal tools. I want the query and the parameters, and to put them into `context.Database.ExecuteSqlCommand(query, parameters)` like in that linked question. – lonix Apr 03 '22 at 08:36
  • 1
    EFC 6.0 `ToQueryString()` includes the parameters and their values before the SQL text (using the db provider syntax, for instance `DECLARE @{param_name} = {param_value}` SqlServer statements). You can browse the `ToQueryString` implementation in their GitHub repository and see how they do it. If you need it just for execution, EFC 6.0 `ToQueryString()` is ready for (non parameterized) execution. But note that it can't be used for split queries. So, it is complicated :) – Ivan Stoev Apr 03 '22 at 08:38
  • 1
    Well, if you need `Delete` or other stuff, just use this extension [inq2db.EntityFrameworkCore](https://github.com/linq2db/linq2db.EntityFrameworkCore) – Svyatoslav Danyliv Apr 03 '22 at 09:19

0 Answers0