Search code examples
entity-frameworkentity-framework-4linq-to-entitiesobjectquery

Get SQL commandtext and parameters from EntityFramework ObjectQuery


I have some queries that EF is unable to support: spatial, indexhints, etc. etc. Most of the data however is EF friendly and I can use the linq provider.

Example: I have Person, PersonAddress and Address tables. On Address I have a spatial index that must be used to define an area for the search. Based on that I want to filter further e.g. on Person.BirthDate. I already have this implemented in T-SQL, but only with fixed parameters.

Instead I want to combine the spatial, and the entity framework queries, and to do that I need to get the SQL command text and parameters from an ObjectQuery. When I have those combinding these will be easy. Unfortunately I can only get the command text using ObjectQuery.ToTraceString().

I'm using linqpad, and I see that it is able to get both parameters and text, so this must be possible.

What is the best way to achieve this?


Solution

  • LinqPad is the most probably using something similar to all tracing and profiling tools. Check tracing wrapper for the sample. It is just wrapper for a provider generating SQL queries but on a wrapper level you have absolutely no knowledge about type of executed query. It is just DbCommand. The only way to modify SQL when you have context of executed linq query is in custom provider.