如何获取实体框架查询的参数? [英] How can I get the parameters of an Entity Framework query?
问题描述
如果我创建 IQueryable<T>
的查询,我可以调用 .ToString() 来获取将被调用的 SQL,但该 SQL 可能包含 @p__linq__0、@p__linq__1、等有没有办法从 IQueryable<T>
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>
推荐答案
根据我的经验,这非常复杂,但这段代码让我明白了:
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(); // this will populate the parameters collection
foreach (var objectParam in objectQuery.Parameters)
{
Console.WriteLine($"{objectParam.Name} = {objectParam.Value.ToString()}");
}
请注意,此代码仅适用于 IQueryable<T>
对象,这些对象实际上是 DbQuery<T>
,由实体框架创建.如果您打算将其包装在实用方法中,则可能需要进行一些类型检查.
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.
这篇关于如何获取实体框架查询的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!