AspNetCoreOData icon indicating copy to clipboard operation
AspNetCoreOData copied to clipboard

Custom OData serializer to ignore empty ComplexType

Open akhilkohlimicrosoft opened this issue 3 years ago • 2 comments
trafficstars

Hello,

I have a entityset that contains Collection of ComplexType, Collection of EntityType and primitive types public class Test { String id; IEnumerable<MockEntityType> mockEntityType{ get; set; } IEnumerable<MockComplexType> mockComplexType{ get; set; } }

Expected behavior is if mockEntityType is empty or mockComplexType is empty, it should not return in response. However, currently only this behavior holds good for mockEntityType and not mockComplexType.

ExpectedOutput:- { id:"123"; }

Actual Output:- { id:"123"; mockComplexType:[] }

Can empty List of ComplexType be ignored?

akhilkohlimicrosoft avatar Jun 02 '22 05:06 akhilkohlimicrosoft

This is not a response to your question, but a question: why do you want this behavior in the first place? I'm sure you realize it if fairly nonstandard, and the more nonstandard stuff you support, the more complex and hard to maintain your codebase gets.

Just trying to understand the underlying need here.

julealgon avatar Jun 03 '22 14:06 julealgon

As per the OData spec, collections cannot be null but they can be empty. Normally, navigation properties are not automatically expanded and included in the response and that's why the collection of entities is not included in your response which means that it might not be null or empty.

If therefore you do not want to include the collection of complex-properties if it is null in your response which is non-standard, you need to use custom-serializers to do so. In the custom serializer you can choose not to return the collection if it is empty.

Look at an example here on how to do it: https://github.com/xuzhg/WebApiSample/tree/main/CustomSerializerSample

ElizabethOkerio avatar Jun 07 '22 17:06 ElizabethOkerio

@akhilkohlimicrosoft I think we have the solution for this. Check it at: https://devblogs.microsoft.com/odata/extension-omit-null-value-properties-in-asp-net-core-odata/

please file new issue if have new questions.

xuzhg avatar Jan 12 '23 19:01 xuzhg