2
votes

How can I apply the query options on a non clr type. The .ApplyTo method is throwing an error when I'm using it.

Error:

"The query option is not bound to any CLR type. 'ApplyTo' is only supported with a query option bound to a CLR type."

var x = (EdmCollectionType)Request.GetODataPath().EdmType;
ODataQueryContext queryContext = new ODataQueryContext(Request.GetEdmModel(), x.ElementType.Definition);
ODataQueryOptions queryOptions = new ODataQueryOptions(queryContext, Request);

//codes.....

queryOptions.ApplyTo(Products);
2

2 Answers

0
votes

Just as the error said, the query options can't be applied on a non clr type now.

It is because now webapi need the clr type to generate linq expression for query options.

However you can implement the ApplyTo function on a non clr type yourself with the raw values in the query options:

queryOptions.Filter.RawValue
queryOptions.OrderBy.RawValue
...
0
votes
ODataQueryContext queryContext = new ODataQueryContext(Request.GetEdmModel(), x.ElementType.Definition);

In the above line, we need to explicitly pass the Class Type obj to ODataQueryContext. Let's assume a type named A which has been created at runtime.

Type a = //Get the type at runtime ;
ODataQueryContext queryContext = new ODataQueryContext(Request.GetEdmModel(), a);

This should resovle the exception.

Now, come to ApplyTo() we can pass an instance of type A to it.

object instance = Activator.CreateInstance(a);
odataQuerySetting.ApplyTo(instance,, new ODataQuerySettings() { });

However, we would like to run ApplyTo() against a list of objects as well as one instance. Array class could help us to accomplish this. Suppose we need to create 10 instances:

Array values = Array.CreateInstance(a, 10);
for (int i = 0; i < 10; i++)
        {
            values.SetValue(Activator.CreateInstance(t), i);
        }

Needless to say that we can add properties to our instances as we would like to and then pass it to SetValue(). Finally, the ApplyTo() can be executed against our list as follow:

  queryOptions.ApplyTo(values.AsQueryable());

Note: if you get the status:406 then one possible cause could be the JsonFormat. use a custom MediaTypeFormatter to resolve that.

I hope that this might help someone.