I am trying to create a dynamic query on a XElement source by using expression trees. A part of this query needs to compare the value of an XElement Attribute and it is when constructing the expressions for obtaining the attribute value I am getting the ArgumentNullException. It is connected to the Expression.Call for XName.Get but I do not know how to interpret the exception in for this case.
PS: the constant expressions in the code are there just for this example.
The code:
var value =
Expression.Property(
Expression.Call(Expression.Parameter(typeof(XElement), "attr1"), typeof(XElement).GetMethod("Attribute"),
Expression.Call(typeof(XName).GetMethod("Get", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly), Expression.Constant("id"))),
"Value");
typeof(XName).GetMethod(
"Get", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
This is your problem, as PetSerAl already pointed out. But removing BindingFlags.Instance
won't solve anything, you need to specify that you want a static method:
typeof(XName).GetMethod(
"Get", BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly)
This still won't work, it throws AmbiguousMatchException
, but we're getting closer. Your Call
has a single string
parameter, so we need to specify we want that overload of XName.Get
:
typeof(XName).GetMethod("Get", new[] { typeof(string) })
(We don't need to specify BindingFlags
, because the default works fine.)
With this modification, your snippet seems to work fine.