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

坚强是说给别人听的谎言 提交于 2019-11-29 12:16:54

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!