MapODataRoute and ODataQueryOptions

I am creating a WebAPI OData solution that processes objects of untyped objects as described in this excellent post . Like this post, I define the preset of EdmModel and use the MapODataRoute method and pass in the model used:

config.Routes.MapODataRoute("odata", "odata", ModelBuilder.GetEdmModel()); 

However, this does not seem to work with the ODataQueryOptions parameter in my methods:

 Get(ODataQueryOptions query) { } 

It gives the following error: this model does not contain the type "System.Web.Http.OData.IEdmEntityObject". Parameter Name: elementClrType

Is there a way to get ODataQueryOptions to work with MapODataRoute?

+2
source share
2 answers

You must create ODataQueryOptions manually in your controller action in untyped mode. Below is a sample code,

 ODataPath path = Request.GetODataPath(); IEdmType edmType = path.EdmType; IEdmType elementType = edmType.TypeKind == EdmTypeKind.Collection ? (edmType as IEdmCollectionType).ElementType.Definition : edmType; // build the typeless query options using the element type. ODataQueryContext queryContext = new ODataQueryContext(Request.GetEdmModel(), elementType); ODataQueryOptions queryOptions = new ODataQueryOptions(queryContext, Request); 
+3
source

I managed to do it as follows:

 ODataPath path = Request.GetODataPath(); IEdmType edmType = path.EdmType; private ODataQueryOptions GetODataQueryOptions(IEdmType edmType) { IEdmModel model = Models.ModelBuilder.GetEdmModel(); ODataQueryContext queryContext = new ODataQueryContext(model, edmType); ODataQueryOptions queryOptions = new ODataQueryOptions(queryContext, this.Request); return queryOptions; } 

This works for most query parameters, but with $ select and $ expand errors: type 'Collection ([Org.Microsoft.Product Nullable = False])' is not an entity type. Only object types support $ select and $ expand. Is there a way to avoid this exception gracefully when the client is trying to filter with $ select and $ expand, or should I just write something like

 if (Request.RequestUri.Query.Contains("select")) { return errormessage } 

Also, more importantly, how to apply these query parameters to the EdmEntityObjectCollection, which is returned in the first method?

 queryOptions.ApplyTo(collectionProduct.AsQueryable()); // wont work... 

(it might be better to use the dynamic assembly of your collection regarding query parameters)

0
source

Source: https://habr.com/ru/post/1235387/


All Articles