Odata netcore — $select and $expand break ODataQueryOptions — solution

Using AutoMapper with Microsoft.AspNet.OData will fail when you try the expand nested objects or select specific properties.

Christian Marinelli
2 min readApr 28, 2021

Almost all options of type ODataQueryOptions work correctly when ApplyTo + any aggregate function is executed, except for Select and Expand (SelectExpand), when you try to use one of these two options it returns this error Unable to cast object of type (SelectExpandBinder+SelectSome / SelectExpandBinder+SelectAllAndExpand).

It is necessary to be clear that before executing ApplyTo + any aggregate function it is necessary to know what type of data is going to be obtained and for this reason we must cast the result to the entity we need.

Can cast the result in various ways, I will show you two ways

  1. Specify the type that you are casting to in parentheses in front of the value or variable to be converted.
  2. Use the Cast extension method.

Problem — Unable to cast object

When expand or select option of type ODataQueryOptions is specified, ApplyTo + any aggregate function is executed this returns dynamic data. This result causes the error because it tries to cast dynamic data to the entity and the system is unable to perform the conversion.

This error does not happen with the other options of type ODataQueryOptions because they do not return dynamic data.

Here is an example so you can better understand the problem

I have two entities Category and Subcategory with a relationship of one to many. Category has four properties (Id, Name, Description, subcategories).
Subcategory has three properties (Id, CategoryId, Name).

I want to get all the categories but only the id and the names of each one, the odata query would be ?$Select=id, name

When indicating the select option and executing ApplyTo + any aggregate function, the select option forces to return dynamic data because category has four properties and only two are being selected, this makes the results stop being Category entities and become dynamic entities. The same happens with the expand option

Solution

Convert all the result to a string and then convert it to a specific type, in our previous example the type was Category. We can do this thanks to Newtonsoft serializing and deserializing the result.
You must install the Newtonsoft.json package.

--

--