How can I get the parameters of an Entity Framework query?

entity-framework entity-framework-6

Question

If I create a query of IQueryable<T>, I can call .ToString() to get the SQL that will be called, but that SQL may contain parameters like @p__linq__0, @p__linq__1, etc. Is there a way to get those parameters and their values from the IQueryable<T>

1
2
6/24/2016 1:55:36 PM

Accepted Answer

It's frustratingly complicated, in my experience, but this code got me there:

        var dbQuery = (DbQuery<T>)query;
        // get the IInternalQuery internal variable from the DbQuery object
        var iqProp = dbQuery.GetType().GetProperty("InternalQuery", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
        var iq = iqProp.GetValue(dbQuery, null);
        // get the ObjectQuery internal variable from the IInternalQuery object
        var oqProp = iq.GetType().GetProperty("ObjectQuery", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
        var objectQuery = (ObjectQuery<T>)oqProp.GetValue(iq, null);

        var sqlString = objectQuery.ToTraceString();
        foreach (var objectParam in objectQuery.Parameters)
        {
            Console.WriteLine($"{objectParam.Name} = {objectParam.Value.ToString()}");
        }

Note that this code only works for IQueryable<T> objects that are actually DbQuery<T>, as are created by entity framework. If you intend to wrap this in a utility method, some type checking may be in order.

7
6/24/2016 2:08:37 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow