Sunday, October 6, 2024

OData! my Data!

Summary: How to process OData filters in C#.

I spent a few days at work trying to figure out how to validate OData filters for the project I'm working on. So, I'd like to share a piece of code that performs basic OData parsing. But before I get to code, let me explain what I'm doing here and why.

We're using ASP.NET Core (.NET 8) to build REST APIs which talk to extrnal REST APIs and we need a consistent way to define the search queries (or search filters) used by the HTTP GET operations. There are different ways to define search queries. For example, SCIM filtering spec looks simple and robust, but after spending the last decade dealing with SCIM implementations, I do not want to have anything to do with SCIM anymore.

The most reasonable option (other than building one from scratch) would be using OData. OData comes with a lot of goodies, but for our use case, we only needed to figure out how to parse and validate OData filters. I thought in .NET Core, handling OData queries would be simple, but unfortunately, the good people at Microsoft must have assumed that everyone using OData in their custom controllers would rely on entity frameworks, so they made it easy for the apps that integrate OData with their entity data models. Which is not what we do. In our case, we take a search query, validate it, and pass to an external API. What this API does with it, we do not care, but we want to be good citizens and not hand it garbage (and in case we get garbage from the clients, we want to send them meaningful errors explaining why their queries are garbage). To do this, we need to take an OData filter expression from a query string and make sure that it is valid. Should be simple, right?

There are many articles explaining how to integrate OData into the REST API controllers, but the only two posts I found useful for our use case were:

By trial and error, I built a simple program that validates and parses a string holding an OData filter. This program is not perfect (it does not handle all possible functions, operators, and complex scenarios), but for us, it is more than enough. I will make it more robust and implement the logic as a library at some point, but if you need a more or less simple example, showing how to validate and parse a not very complex OData filter, see code below (read the comments that explain the requirements and dependencies).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
/*
This .NET Core console app was built and tested with the following Nuget packages {versions}:
 
- Microsoft.AspNetCore.OData {9.0.0}
- Microsoft.Extensions.DependencyInjection.Abstractions {8.0.1}
- Microsoft.OData.Core {8.0.1}
 
To install the latest versions of the packages, run from Package Manager Console:
 
Install-Package Microsoft.Extensions.DependencyInjection.Abstractions
Install-Package Microsoft.OData.Core
Install-Package Microsoft.AspNetCore.OData
 
SUMMARY:
 
This program illustrates how to validate and parse basic OData filters in the given text strings.
The code may not be comprehensive and it does not cover advanced OData use cases,
but it shows how to handle typical filter conditions that utilize common operations
and functions ('not', 'eq', 'ne', 'gt', 'ge', 'lt', 'le', 'startsWith', 'endsWith',
'contains', 'in') and grouped using logical operators ('and', 'or').
 
The filter properties will be mapped to properties of the filter object properties. The filter
objects (there is more than one) identify how OData filter attributes can be mapped to a real
entity that may come from an external resource, such as a web service, database, report, etc.
*/
 
// The following namespace holds the classes used in the OData filter.
#pragma warning disable IDE0130 // Namespace does not match folder structure
namespace TestOData1;
#pragma warning restore IDE0130 // Namespace does not match folder structure
 
using Microsoft.OData.Edm;
using Microsoft.OData.ModelBuilder;
using Microsoft.OData.UriParser;
using System.Linq;
 
/// <summary>
/// Main program.
/// </summary>
internal class Program
{
    #region Properties
    // Use the same separator for complex (nested) types as the OData filters.
    private static readonly string _separator = "/";
 
    // Number of indent characters for the binary tree output.
    private static readonly int _indentLength = 2;
 
    // Set this value to true to print object names of the tree nodes.
    private static readonly bool _printNode = false;
    #endregion
 
    #region Filter examples
    // Here are some basic filter we may want to test.
 
    // By default, property names are case-insensitive, but we'll make them case-insensitive.
    private static readonly string[] _filters =
    [
        "not(enabled)",
        "not(true)",
        "email eq null",
        "email ne null",
        "email eq 'john@mail.com'",
        "email ne 'john@mail.com'",
        "email eq displayName",
        "email ne displayName",
        "contains(email, '@')",
        "not contains(email, '@')",
        "contains(email, displayName)",
        "not contains(email, displayName)",
        "startsWith(email, 'john')",
        "not startsWith(email, 'john')",
        "endsWith(email, '@mail.com')",
        "not endsWith(email, '@mail.com')",
        "email in ('john@mail.com', 'mary@mail.com')",
        "not (email in ('john@mail.com', 'mary@mail.com'))",
        "id eq 0",
        "id gt 0",
        "id lt 2000",
        "id ge 1",
        "id le 2000",
        "name eq null",
        "name ne null",
        "name/givenName eq null",
        "sponsor/name/givenName eq null",
        "name/surname ne sponsor/name/surname",
        "name/givenName in ('John', 'Mary')",
        "name/givenName ne name/nickName",
        "startsWith(displayName, 'J')",
        "type eq 'Employee'",
        "type eq 'Guest' and name/Surname eq 'Johnson'",
        "type eq 'Contractor' and not(endsWith(email, '@mail.com'))",
        "enabled eq false and type in ('Employee', 'Contractor') ",
        "(enabled eq true and type eq 'Employee') or (enabled eq false and (type eq 'Guest' or endsWith(email, '@mail.com')))",
        "phoneNumbers/any(p: p eq '123-456-6789')",
        "socialLogins/any(s: s/name eq 'Facebook')",
        "socialLogins/any(s: s/name eq 'Facebook' or endsWith(s/url, 'google.com'))",
        "sponsor/phoneNumbers/any(p: p eq '123-456-6789')",
        "sponsor/socialLogins/any(s: s/name eq 'Facebook')"
    ];
    #endregion
 
    #region Main method
    private static void Main()
    {
        // The builder is responsible for mapping OData filter conditions to the object properties.
        ODataConventionModelBuilder builder = new();
 
        // UserFilter defines the properties which can be used in our filter (this class is defined below).
        // The UserFilter class properties also can be based on other complex types, but they will be
        // included implicitly, so no need to reference them.
        builder.AddEntityType(typeof(User));
 
        // EDM (Entity Data Model) encapsulates classes that will be used in the OData filters.
        IEdmModel model = builder.GetEdmModel();
 
        // Let's print all classes that our EDM schema recognizes.
        Console.WriteLine("ODATA SCHEMA ELEMENTS:");
        foreach (IEdmSchemaElement element in model.SchemaElements)
        {
            Console.WriteLine($"- {element.FullName()}: {element.SchemaElementKind}");
        }
 
        // If you define the EDM classes not under an explicitly defined namespace,
        // make sure you add 'Default.' to the full name because 'Default' would be the implicit
        // namespace created by the compiler; if you do not, these types will not be found.
        // string qualifiedName = "Default." + typeof(GroupFilter).FullName;
        string qualifiedName = typeof(User).FullName ?? "";
 
        // Now, lets use our filter class as the EDM type, so it can be used for OData filter handling.
        IEdmType type = model.FindDeclaredType(qualifiedName);
        if (type == null)
        {
            Console.WriteLine($"Type '{qualifiedName}' is not found in the OData schema model.");
            return;
        }
 
        foreach (string filter in _filters)
        {
            Console.WriteLine();
            Console.WriteLine(new string('-', 72));
            Console.WriteLine("EXPRESSION: " + filter);
            Console.WriteLine(new string('-', 72));
 
            // This dictionary can include other OData parameters,
            // such as "$top", "$skip", "$count", "$select", "$orderby", "$search", etc.
            // but we are only interested in the filter.
            Dictionary<string, string> options = new()
            {
                {"$filter", filter}
            };
 
            try
            {
                ODataQueryOptionParser parser = new(model, type, null, options)
                {
                    // By default, property names are case-sensitive,
                    // so we need to explicitly specify them to be case-insensitive.
                    Resolver = new ODataUriResolver() { EnableCaseInsensitive = true }
                };
 
                FilterClause clause = parser.ParseFilter();
 
                if (clause == null)
                {
                    Console.WriteLine("FilterClause is null.");
                }
                else
                {
                    ProcessNode(clause.Expression, 0, null);
                }
            }
            catch (Exception ex)
            {
                while (ex != null)
                {
                    Console.WriteLine(ex.Message + " ");
 
                    if (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                    }
                    else
                    {
                        break;
                    }
                }
                Console.WriteLine();
            }
        }
    }
    #endregion
 
    #region Node processing methods
    /// <summary>
    /// Process a node of the OData filter.
    /// </summary>
    /// <param name="node">
    /// Node to process.
    /// </param>
    /// <param name="level">
    /// Indent level of this node.
    /// </param>
    /// <param name="parentName">
    /// Name of the parent property of the nodes under the 'Any' operator.
    /// </param>
    /// <remarks>
    /// OData filter is basically a binary tree, so we'll process it as such.
    /// </remarks>
    private static void ProcessNode
    (
        SingleValueNode node,
        int level,
        string? parentName
    )
    {
        // The filter tree consists of nodes all of which are directly derived from SingleValueNode.
        if (node == null)
        {
            // Shouldn't happen, but just in case.
            return;
        }
        else if (node is BinaryOperatorNode binaryOperatorNode)
        {
            ProcessBinaryOperatorNode(binaryOperatorNode, level, parentName);
        }
        else if (node is SingleComplexNode singleComplexNode)
        {
            ProcessSingleComplexNode(singleComplexNode, level, parentName);
        }
        else if (node is SingleValueFunctionCallNode singleValueFunctionCallNode)
        {
            ProcessSingleValueFunctionCallNode(singleValueFunctionCallNode, level, parentName);
        }
        else if (node is SingleValueOpenPropertyAccessNode singleValueOpenPropertyAccessNode)
        {
            ProcessSingleValueOpenPropertyAccessNode(singleValueOpenPropertyAccessNode, level, parentName);
        }
        else if (node is SingleValuePropertyAccessNode singleValuePropertyAccessNode)
        {
            ProcessSingleValuePropertyAccessNode(singleValuePropertyAccessNode, level, parentName);
        }
        else if (node is InNode inNode)
        {
            ProcessInNode(inNode, level, parentName);
        }
        else if (node is ConstantNode constantNode)
        {
            ProcessConstantNode(constantNode, level);
        }
        else if (node is ConvertNode convertNode)
        {
            ProcessConvertNode(convertNode, level, parentName);
        }
        else if (node is UnaryOperatorNode unaryOperatorNode)
        {
            ProcessUnaryOperatorNode(unaryOperatorNode, level, parentName);
        }
        else if (node is AnyNode anyNode)
        {
            ProcessAnyNode(anyNode, level);
        }
        else if (node is NonResourceRangeVariableReferenceNode nonResourceRangeVariableReferenceNode)
        {
            ProcessNonResourceRangeVariableReferenceNode(nonResourceRangeVariableReferenceNode, level, parentName);
        }
        else
        {
            // There may be more node types that need to be handled explicitly,
            // but for now, let's handle all unexpected nodes as a simple node.
            ProcessSingleValueNode(node, level);
        }
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="param"/>
    /// <summary>
    /// Handles all kinds of nodes,
    /// e.g. holding elements that must be converted to a certain data type, such as enum,
    /// operator nodes, value nodes, etc.
    /// </summary>
    private static void ProcessConvertNode
    (
        ConvertNode node,
        int level,
        string? parentName
    )
    {
        ProcessNode(node.Source, level, parentName);
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="params"/>
    /// <summary>
    /// Handles the simplest node holding a single element.
    /// </summary>
    /// <remarks>
    /// This method will also handle any nodes that are not handled by the node type-specific methods.
    /// </remarks>
    private static void ProcessSingleValueNode
    (
        SingleValueNode node,
        int level
    )
    {
        if (_printNode)
        {
            WriteLine(level, FormatNode(node.Kind));
        }
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="param"/>
    /// <summary>
    /// Handles a node holding a simple constant value, such as a string, a number, or a boolean.
    /// </summary>
    private static void ProcessConstantNode
    (
        ConstantNode node,
        int level
    )
    {
        WriteLine(level, FormatValue(node.Value ?? "(null)"));
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="param"/>
    /// <summary>
    /// Handles values in the collection object (such as a collection inside of the 'in' clause).
    /// </summary>
    private static void ProcessCollectionConstantNode
    (
        CollectionConstantNode node,
        int level,
        string? parentName
    )
    {
        foreach(var value in node.Collection)
        {
            ProcessNode(value, level, parentName);
        }
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="param"/>
    /// <summary>
    /// Handles a node holding a complex (i.e. nested) object property.
    /// </summary>
    private static void ProcessSingleComplexNode
    (
        SingleComplexNode node,
        int level,
        string? parentName
    )
    {
        WriteLine(level, FormatProperty(node.Property.Name));
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="param"/>
    /// <summary>
    /// Handles a node holding a simple object property.
    /// </summary>
    private static void ProcessSingleValuePropertyAccessNode
    (
        SingleValuePropertyAccessNode node,
        int level,
        string? parentName
    )
    {
        WriteLine(level, FormatProperty(GetPropertyName(node, parentName)));
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="param"/>
    /// <summary>
    /// Not sure what node this is, but based on the name it should be similar to SingleValuePropertyAccessNode.
    /// </summary>
    private static void ProcessSingleValueOpenPropertyAccessNode
    (
        SingleValueOpenPropertyAccessNode node,
        int level,
        string? parentName
    )
    {
        WriteLine(level, FormatProperty(GetPropertyName(node, parentName)));
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="params"/>
    /// <summary>
    /// Handles the nodes holding dynamic value such as aliases use in the 'Any' operator.
    /// </summary>
    private static void ProcessNonResourceRangeVariableReferenceNode
    (
        NonResourceRangeVariableReferenceNode node,
        int level,
        string? parentName
    )
    {
        // In filter 'phoneNumbers/any(p: p eq '123-456-6789')', since 'p' is just an alias,
        // we want to print 'phoneNumbers' because it is the name of the collection to
        // to which the filter is applied.
 
        // This node should be under a parent's 'Any' operation.
        if (!string.IsNullOrEmpty(parentName))
        {
            WriteLine(level, FormatProperty(parentName));
        }
        // But just in case, we can just print the alias (e.g. 'p' in our example).
        else
        {
            WriteLine(level, FormatProperty(node.RangeVariable.Name));
        }
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="param"/>
    /// <summary>
    /// Handles a unary operation node, such as 'not'.
    /// </summary>
    private static void ProcessUnaryOperatorNode
    (
        UnaryOperatorNode node,
        int level,
        string? parentName
    )
    {
        ProcessSingleValueNode(node, level);
 
        WriteLine(level, FormatOperator(node.OperatorKind));
 
        ProcessNode(node.Operand, level + 1, parentName);
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="param"/>
    /// <summary>
    /// Handles an any operation applicable to arrays, lists and collections.
    /// </summary>
    private static void ProcessAnyNode
    (
        AnyNode node,
        int level
    )
    {
        ProcessSingleValueNode(node, level);
 
        WriteLine(level, FormatOperator(node.Kind));
 
        string? parentName = null;
 
        if (node.Source is CollectionPropertyAccessNode collectionPropertyAccessNode)
        {
            parentName = GetPropertyName(collectionPropertyAccessNode, null);
        }
        else if (node.Source is CollectionComplexNode collectionComplexNode)
        {
            parentName = GetPropertyName(collectionComplexNode, null);
        }
 
        if (!string.IsNullOrEmpty(parentName))
        {
            WriteLine(level + 1, FormatProperty(parentName));
            ProcessNode(node.Body, level + 2, parentName);
        }
        else
        {
            ProcessNode(node.Body, level + 1, null);
        }
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="param"/>
    /// <summary>
    /// Handles a node holing an 'in' operation.
    /// </summary>
    private static void ProcessInNode
    (
        InNode node,
        int level,
        string? parentName
    )
    {
        ProcessSingleValueNode(node, level);
 
        WriteLine(level, FormatOperator(node.Kind));
 
        // The left element of the in node holds the property name.
        if (node.Left is SingleValuePropertyAccessNode singleValuePropertyAccessNode &&
            !string.IsNullOrEmpty(singleValuePropertyAccessNode.Property?.Name))
        {
            WriteLine(level + 1, FormatProperty(GetPropertyName(singleValuePropertyAccessNode.Property?.Name ?? "", parentName)));
        }
        else if (node.Left is SingleValueOpenPropertyAccessNode singleValueOpenPropertyAccessNode &&
            !string.IsNullOrEmpty(singleValueOpenPropertyAccessNode.Name))
        {
            WriteLine(level + 1, FormatProperty(GetPropertyName(singleValueOpenPropertyAccessNode.Name ?? "", parentName)));
        }
 
        // The right element of the in node holds the collection of the values.
        if (node.Right is CollectionConstantNode collectionConstantNode)
        {
            ProcessCollectionConstantNode(collectionConstantNode, level + 1, parentName);
        }
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="param"/>
    /// <summary>
    /// Handles a node holding a function call, such as 'startsWith', 'contains', etc.
    /// </summary>
    private static void ProcessSingleValueFunctionCallNode
    (
        SingleValueFunctionCallNode node,
        int level,
        string? parentName
    )
    {
        ProcessSingleValueNode(node, level);
 
        WriteLine(level, FormatOperator(node.Name));
 
        // The first item in the array of parameters holds the property being used in the function.
        if (node.Parameters.FirstOrDefault() is SingleValuePropertyAccessNode param)
        {
            WriteLine(level + 1, FormatProperty(GetPropertyName(param.Property.Name, parentName)));
        }
 
        // The rest of the items must be constants.
        IEnumerable<QueryNode> values = node.Parameters.Skip(1);
 
        foreach (QueryNode value in values)
        {
            if (value is SingleValueNode singleValue)
            {
                ProcessNode(singleValue, level + 1, parentName);
            }
        }
    }
 
    /// <inheritdoc cref="ProcessNode(SingleValueNode, int, string?)" path="param"/>
    /// <summary>
    /// Handles a binary operator, such as 'eq', 'ne', 'and', 'or', etc.
    /// </summary>
    private static void ProcessBinaryOperatorNode
    (
        BinaryOperatorNode node,
        int level,
        string? parentName
    )
    {
        ProcessSingleValueNode(node, level);
 
        WriteLine(level, FormatOperator(node.OperatorKind));
 
        ProcessNode(node.Left, level + 1, parentName);
        ProcessNode(node.Right, level + 1, parentName);
    }
    #endregion
 
    #region Property name formatting methods
    /// <summary>
    /// Appends name of the parent to the given name if needed.
    /// </summary>
    /// <param name="name">
    /// Name of the property.
    /// </param>
    /// <param name="parentName">
    /// Name of the parent collection property (to which the 'Any' operation is applied).
    /// </param>
    /// <returns>
    /// Property name.
    /// </returns>
    private static string GetPropertyName
    (
        string name,
        string? parentName
    )
    {
        return string.IsNullOrEmpty(parentName)
            ? name
            : parentName + _separator + name;
    }
 
    /// <inheritdoc cref="GetPropertyName(string, string)" path="param|returns"/>
    /// <summary>
    /// Generates the name of the complex (i.e. nested) property that includes the names of all parents.
    /// </summary>
    /// <param name="node">
    /// Property node.
    /// </param>
    private static string GetPropertyName
    (
        SingleValuePropertyAccessNode node,
        string? parentName
    )
    {
        string path = "";
        string parent;
 
        if (node.Source == null)
        {
            return GetPropertyName(node.Property.Name, parentName);
        }
 
        // The source property point to the parent object referencing this property.
        var source = node.Source;
 
        while (source != null)
        {
            // There may be a couple of types used as sources.
            // In our example, UserFilter.Name is a SingleComplexNode,
            // while UserFilter.Sponsor.Name is a SingleNavigationNode.
            // There may be other case, but I'm not sure how to test.
            if (source is SingleComplexNode singleComplexNode &&
                !string.IsNullOrEmpty(singleComplexNode.Property?.Name))
            {
                parent = singleComplexNode.Property.Name ?? "";
                source = singleComplexNode.Source;
            }
            else if (source is SingleNavigationNode singleNavigationNode &&
                !string.IsNullOrEmpty(singleNavigationNode.NavigationProperty?.Name))
            {
                parent = singleNavigationNode.NavigationProperty?.Name ?? "";
                source = singleNavigationNode.Source;
            }
            else
            {
                break;
            }
 
            path = string.IsNullOrEmpty(path)
                ? parent
                : parent + _separator + path;
        }
 
        return string.IsNullOrEmpty(path)
            ? GetPropertyName(node.Property.Name, parentName)
            : GetPropertyName(GetPropertyName(node.Property.Name, path), parentName);
    }
 
    /// <inheritdoc cref="GetPropertyName(SingleValuePropertyAccessNode, string)" path="param|returns"/>
    private static string GetPropertyName
    (
        SingleValueOpenPropertyAccessNode node,
        string? parentName
    )
    {
        string path = "";
        string parent;
 
        if (node.Source == null)
        {
            return GetPropertyName(node.Name, parentName);
        }
 
        // The source property point to the parent object referencing this property.
        var source = node.Source;
 
        while (source != null)
        {
            // There may be a couple of types used as sources.
            // In our example, UserFilter.Name is a SingleComplexNode,
            // while UserFilter.Sponsor.Name is a SingleNavigationNode.
            // There may be other case, but I'm not sure how to test.
            if (source is SingleComplexNode singleComplexNode &&
                !string.IsNullOrEmpty(singleComplexNode.Property?.Name))
            {
                parent = singleComplexNode.Property.Name ?? "";
                source = singleComplexNode.Source;
            }
            else if (source is SingleNavigationNode singleNavigationNode &&
                !string.IsNullOrEmpty(singleNavigationNode.NavigationProperty?.Name))
            {
                parent = singleNavigationNode.NavigationProperty?.Name ?? "";
                source = singleNavigationNode.Source;
            }
            else
            {
                break;
            }
 
            path = string.IsNullOrEmpty(path)
                ? parent
                : parent + _separator + path;
        }
 
        return string.IsNullOrEmpty(path)
            ? GetPropertyName(node.Name, parentName)
            : GetPropertyName(GetPropertyName(node.Name, path), parentName);
    }
 
    /// <inheritdoc cref="GetPropertyName(SingleValuePropertyAccessNode, string)" path="param|returns"/>
    private static string GetPropertyName
    (
        CollectionComplexNode node,
        string? parentName
    )
    {
        string path = "";
        string parent;
 
        if (node.Source == null)
        {
            return GetPropertyName(node.Property.Name, parentName);
        }
 
        // The source property point to the parent object referencing this property.
        var source = node.Source;
 
        while (source != null)
        {
            // There may be a couple of types used as sources.
            // In our example, UserFilter.Name is a SingleComplexNode,
            // while UserFilter.Sponsor.Name is a SingleNavigationNode.
            // There may be other case, but I'm not sure how to test.
            if (source is SingleComplexNode singleComplexNode &&
                !string.IsNullOrEmpty(singleComplexNode.Property?.Name))
            {
                parent = singleComplexNode.Property.Name ?? "";
                source = singleComplexNode.Source;
            }
            else if (source is SingleNavigationNode singleNavigationNode &&
                !string.IsNullOrEmpty(singleNavigationNode.NavigationProperty?.Name))
            {
                parent = singleNavigationNode.NavigationProperty?.Name ?? "";
                source = singleNavigationNode.Source;
            }
            else
            {
                break;
            }
 
            path = string.IsNullOrEmpty(path)
                ? parent
                : parent + _separator + path;
        }
 
        return string.IsNullOrEmpty(path)
            ? GetPropertyName(node.Property.Name, parentName)
            : GetPropertyName(GetPropertyName(node.Property.Name, path), parentName);
    }
 
    /// <inheritdoc cref="GetPropertyName(SingleValuePropertyAccessNode, string)" path="param|returns"/>
    private static string GetPropertyName
    (
        CollectionPropertyAccessNode node,
        string? parentName
    )
    {
        string path = "";
        string parent;
 
        if (node.Source == null)
        {
            return GetPropertyName(node.Property.Name, parentName);
        }
 
        // The source property point to the parent object referencing this property.
        var source = node.Source;
 
        while (source != null)
        {
            // There may be a couple of types used as sources.
            // In our example, UserFilter.Name is a SingleComplexNode,
            // while UserFilter.Sponsor.Name is a SingleNavigationNode.
            // There may be other case, but I'm not sure how to test.
            if (source is SingleComplexNode singleComplexNode &&
                !string.IsNullOrEmpty(singleComplexNode.Property?.Name))
            {
                parent = singleComplexNode.Property.Name ?? "";
                source = singleComplexNode.Source;
            }
            else if (source is SingleNavigationNode singleNavigationNode &&
                !string.IsNullOrEmpty(singleNavigationNode.NavigationProperty?.Name))
            {
                parent = singleNavigationNode.NavigationProperty?.Name ?? "";
                source = singleNavigationNode.Source;
            }
            else
            {
                break;
            }
 
            path = string.IsNullOrEmpty(path)
                ? parent
                : parent + _separator + path;
        }
 
        return string.IsNullOrEmpty(path)
            ? GetPropertyName(node.Property.Name, parentName)
            : GetPropertyName(GetPropertyName(node.Property.Name, path), parentName);
    }
 
    #endregion
     
    #region Output formatting methods
    /// <summary>
    /// Formats node message.
    /// </summary>
    /// <param name="name">
    /// Name of the node.
    /// </param>
    /// <returns>
    /// Formatted node message.
    /// </returns>
    private static string FormatNode
    (
        object name
    )
    {
        return "NODE: " + name;
    }
 
    /// <summary>
    /// Formats operator message.
    /// </summary>
    /// <param name="name">
    /// Name of the operator.
    /// </param>
    /// <returns>
    /// Formatted operator message.
    /// </returns>
    private static string FormatOperator
    (
        object name
    )
    {
        return "OPERATOR: " + name;
    }
 
    /// <summary>
    /// Formats property message.
    /// </summary>
    /// <param name="name">
    /// Name of the property.
    /// </param>
    /// <returns>
    /// Formatted property message.
    /// </returns>
    private static string FormatProperty
    (
        object name
    )
    {
        return "PROPERTY: " + name;
    }
 
    /// <summary>
    /// Formats value message.
    /// </summary>
    /// <param name="name">
    /// Name of the value.
    /// </param>
    /// <returns>
    /// Formatted value message.
    /// </returns>
    private static string FormatValue
    (
        object name
    )
    {
        return "VALUE: " + name;
    }
    #endregion
 
    #region Print functions
    /// <summary>
    /// Prints text with appropriate indentation.
    /// </summary>
    /// <param name="indentLevel">
    /// Indentation level.
    /// </param>
    /// <param name="message">
    /// Message text.
    /// </param>
    /// <param name="args">
    /// Optional message parameters.
    /// </param>
    private static void WriteLine
    (
        int indentLevel,
        string message,
        params object[] args
    )
    {
        string indent = new(' ', indentLevel * _indentLength);
        Console.WriteLine(indent + message, args);
    }
    #endregion
}
 
#region Data models used by the OData filter
/// <summary>
/// Defines types of users.
/// </summary>
public enum UserType
{
    Employee,
    Contractor,
    Guest
}
 
/// <summary>
/// Defines name parts.
/// </summary>
public class PersonName
{
    public string? GivenName
    {
        get; set;
    }
 
    public string? NickName
    {
        get; set;
    }
 
    public string? Surname
    {
        get; set;
    }
 
    public char? MiddleInitial
    {
        get; set;
    }
}
 
/// <summary>
/// Defines social login info.
/// </summary>
public class SocialLogin
{
    public string? Name
    {
        get; set;
    }
 
    public string? Url
    {
        get; set;
    }
}
 
/// <summary>
/// Primary filter object (it may not necessarily correspond to the corresponding backend entity).
/// </summary>
public class User
{
    public int? Id
    {
        get; set;
    }
 
    public UserType? Type
    {
        get; set;
    }
 
    public PersonName? Name
    {
        get; set;
    }
 
    public string? DisplayName
    {
        get; set;
    }
 
    public string? Email
    {
        get; set;
    }
 
    public bool? Enabled
    {
        get; set;
    }
 
    // Use this property to test complex properties (it can be nested indefinitely).
    public User? Sponsor
    {
        get; set;
    }
 
    public string[]? PhoneNumbers
    {
        get; set;
    }
 
    public List<SocialLogin>? SocialLogins
    {
        get; set;
    }
}
#endregion

Here is the program output:

ODATA SCHEMA ELEMENTS:
- TestOData1.User: TypeDefinition
- TestOData1.PersonName: TypeDefinition
- TestOData1.SocialLogin: TypeDefinition
- TestOData1.UserType: TypeDefinition
- Default.Container: EntityContainer

------------------------------------------------------------------------
EXPRESSION: not(enabled)
------------------------------------------------------------------------
OPERATOR: Not
  PROPERTY: Enabled

------------------------------------------------------------------------
EXPRESSION: not(true)
------------------------------------------------------------------------
OPERATOR: Not
  VALUE: True

------------------------------------------------------------------------
EXPRESSION: email eq null
------------------------------------------------------------------------
OPERATOR: Equal
  PROPERTY: Email
  VALUE: (null)

------------------------------------------------------------------------
EXPRESSION: email ne null
------------------------------------------------------------------------
OPERATOR: NotEqual
  PROPERTY: Email
  VALUE: (null)

------------------------------------------------------------------------
EXPRESSION: email eq 'john@mail.com'
------------------------------------------------------------------------
OPERATOR: Equal
  PROPERTY: Email
  VALUE: john@mail.com

------------------------------------------------------------------------
EXPRESSION: email ne 'john@mail.com'
------------------------------------------------------------------------
OPERATOR: NotEqual
  PROPERTY: Email
  VALUE: john@mail.com

------------------------------------------------------------------------
EXPRESSION: email eq displayName
------------------------------------------------------------------------
OPERATOR: Equal
  PROPERTY: Email
  PROPERTY: DisplayName

------------------------------------------------------------------------
EXPRESSION: email ne displayName
------------------------------------------------------------------------
OPERATOR: NotEqual
  PROPERTY: Email
  PROPERTY: DisplayName

------------------------------------------------------------------------
EXPRESSION: contains(email, '@')
------------------------------------------------------------------------
OPERATOR: contains
  PROPERTY: Email
  VALUE: @

------------------------------------------------------------------------
EXPRESSION: not contains(email, '@')
------------------------------------------------------------------------
OPERATOR: Not
  OPERATOR: contains
    PROPERTY: Email
    VALUE: @

------------------------------------------------------------------------
EXPRESSION: contains(email, displayName)
------------------------------------------------------------------------
OPERATOR: contains
  PROPERTY: Email
  PROPERTY: DisplayName

------------------------------------------------------------------------
EXPRESSION: not contains(email, displayName)
------------------------------------------------------------------------
OPERATOR: Not
  OPERATOR: contains
    PROPERTY: Email
    PROPERTY: DisplayName

------------------------------------------------------------------------
EXPRESSION: startsWith(email, 'john')
------------------------------------------------------------------------
OPERATOR: startswith
  PROPERTY: Email
  VALUE: john

------------------------------------------------------------------------
EXPRESSION: not startsWith(email, 'john')
------------------------------------------------------------------------
OPERATOR: Not
  OPERATOR: startswith
    PROPERTY: Email
    VALUE: john

------------------------------------------------------------------------
EXPRESSION: endsWith(email, '@mail.com')
------------------------------------------------------------------------
OPERATOR: endswith
  PROPERTY: Email
  VALUE: @mail.com

------------------------------------------------------------------------
EXPRESSION: not endsWith(email, '@mail.com')
------------------------------------------------------------------------
OPERATOR: Not
  OPERATOR: endswith
    PROPERTY: Email
    VALUE: @mail.com

------------------------------------------------------------------------
EXPRESSION: email in ('john@mail.com', 'mary@mail.com')
------------------------------------------------------------------------
OPERATOR: In
  PROPERTY: Email
  VALUE: john@mail.com
  VALUE: mary@mail.com

------------------------------------------------------------------------
EXPRESSION: not (email in ('john@mail.com', 'mary@mail.com'))
------------------------------------------------------------------------
OPERATOR: Not
  OPERATOR: In
    PROPERTY: Email
    VALUE: john@mail.com
    VALUE: mary@mail.com

------------------------------------------------------------------------
EXPRESSION: id eq 0
------------------------------------------------------------------------
OPERATOR: Equal
  PROPERTY: Id
  VALUE: 0

------------------------------------------------------------------------
EXPRESSION: id gt 0
------------------------------------------------------------------------
OPERATOR: GreaterThan
  PROPERTY: Id
  VALUE: 0

------------------------------------------------------------------------
EXPRESSION: id lt 2000
------------------------------------------------------------------------
OPERATOR: LessThan
  PROPERTY: Id
  VALUE: 2000

------------------------------------------------------------------------
EXPRESSION: id ge 1
------------------------------------------------------------------------
OPERATOR: GreaterThanOrEqual
  PROPERTY: Id
  VALUE: 1

------------------------------------------------------------------------
EXPRESSION: id le 2000
------------------------------------------------------------------------
OPERATOR: LessThanOrEqual
  PROPERTY: Id
  VALUE: 2000

------------------------------------------------------------------------
EXPRESSION: name eq null
------------------------------------------------------------------------
OPERATOR: Equal
  PROPERTY: Name
  VALUE: (null)

------------------------------------------------------------------------
EXPRESSION: name ne null
------------------------------------------------------------------------
OPERATOR: NotEqual
  PROPERTY: Name
  VALUE: (null)

------------------------------------------------------------------------
EXPRESSION: name/givenName eq null
------------------------------------------------------------------------
OPERATOR: Equal
  PROPERTY: Name/GivenName
  VALUE: (null)

------------------------------------------------------------------------
EXPRESSION: sponsor/name/givenName eq null
------------------------------------------------------------------------
OPERATOR: Equal
  PROPERTY: Sponsor/Name/GivenName
  VALUE: (null)

------------------------------------------------------------------------
EXPRESSION: name/surname ne sponsor/name/surname
------------------------------------------------------------------------
OPERATOR: NotEqual
  PROPERTY: Name/Surname
  PROPERTY: Sponsor/Name/Surname

------------------------------------------------------------------------
EXPRESSION: name/givenName in ('John', 'Mary')
------------------------------------------------------------------------
OPERATOR: In
  PROPERTY: GivenName
  VALUE: John
  VALUE: Mary

------------------------------------------------------------------------
EXPRESSION: name/givenName ne name/nickName
------------------------------------------------------------------------
OPERATOR: NotEqual
  PROPERTY: Name/GivenName
  PROPERTY: Name/NickName

------------------------------------------------------------------------
EXPRESSION: startsWith(displayName, 'J')
------------------------------------------------------------------------
OPERATOR: startswith
  PROPERTY: DisplayName
  VALUE: J

------------------------------------------------------------------------
EXPRESSION: type eq 'Employee'
------------------------------------------------------------------------
OPERATOR: Equal
  PROPERTY: Type
  VALUE: Employee

------------------------------------------------------------------------
EXPRESSION: type eq 'Guest' and name/Surname eq 'Johnson'
------------------------------------------------------------------------
OPERATOR: And
  OPERATOR: Equal
    PROPERTY: Type
    VALUE: Guest
  OPERATOR: Equal
    PROPERTY: Name/Surname
    VALUE: Johnson

------------------------------------------------------------------------
EXPRESSION: type eq 'Contractor' and not(endsWith(email, '@mail.com'))
------------------------------------------------------------------------
OPERATOR: And
  OPERATOR: Equal
    PROPERTY: Type
    VALUE: Contractor
  OPERATOR: Not
    OPERATOR: endswith
      PROPERTY: Email
      VALUE: @mail.com

------------------------------------------------------------------------
EXPRESSION: enabled eq false and type in ('Employee', 'Contractor')
------------------------------------------------------------------------
OPERATOR: And
  OPERATOR: Equal
    PROPERTY: Enabled
    VALUE: False
  OPERATOR: In
    PROPERTY: Type
    VALUE: Employee
    VALUE: Contractor

------------------------------------------------------------------------
EXPRESSION: (enabled eq true and type eq 'Employee') or (enabled eq false and (type eq 'Guest' or endsWith(email, '@mail.com')))
------------------------------------------------------------------------
OPERATOR: Or
  OPERATOR: And
    OPERATOR: Equal
      PROPERTY: Enabled
      VALUE: True
    OPERATOR: Equal
      PROPERTY: Type
      VALUE: Employee
  OPERATOR: And
    OPERATOR: Equal
      PROPERTY: Enabled
      VALUE: False
    OPERATOR: Or
      OPERATOR: Equal
        PROPERTY: Type
        VALUE: Guest
      OPERATOR: endswith
        PROPERTY: Email
        VALUE: @mail.com

------------------------------------------------------------------------
EXPRESSION: phoneNumbers/any(p: p eq '123-456-6789')
------------------------------------------------------------------------
OPERATOR: Any
  PROPERTY: PhoneNumbers
    OPERATOR: Equal
      PROPERTY: PhoneNumbers
      VALUE: 123-456-6789

------------------------------------------------------------------------
EXPRESSION: socialLogins/any(s: s/name eq 'Facebook')
------------------------------------------------------------------------
OPERATOR: Any
  PROPERTY: SocialLogins
    OPERATOR: Equal
      PROPERTY: SocialLogins/Name
      VALUE: Facebook

------------------------------------------------------------------------
EXPRESSION: socialLogins/any(s: s/name eq 'Facebook' or endsWith(s/url, 'google.com'))
------------------------------------------------------------------------
OPERATOR: Any
  PROPERTY: SocialLogins
    OPERATOR: Or
      OPERATOR: Equal
        PROPERTY: SocialLogins/Name
        VALUE: Facebook
      OPERATOR: endswith
        PROPERTY: SocialLogins/Url
        VALUE: google.com

------------------------------------------------------------------------
EXPRESSION: sponsor/phoneNumbers/any(p: p eq '123-456-6789')
------------------------------------------------------------------------
OPERATOR: Any
  PROPERTY: Sponsor/PhoneNumbers
    OPERATOR: Equal
      PROPERTY: Sponsor/PhoneNumbers
      VALUE: 123-456-6789

------------------------------------------------------------------------
EXPRESSION: sponsor/socialLogins/any(s: s/name eq 'Facebook')
------------------------------------------------------------------------
OPERATOR: Any
  PROPERTY: Sponsor/SocialLogins
    OPERATOR: Equal
      PROPERTY: Sponsor/SocialLogins/Name
      VALUE: Facebook

Enjoy!