ZEXSM / OData.QueryBuilder

OData.QueryBuilder - library for creating complex OData queries (OData version 4.01) based on data models with linq syntax.
MIT License
78 stars 32 forks source link

Multiple column Select doesn't respect ODataPropertyName attribute #131

Open onthepenciltip opened 1 month ago

onthepenciltip commented 1 month ago

Having some class,

public class Thing
{
    [ODataPropertyName("title")]
    public string Title { get; set; }

    [ODataPropertyName("id")]
    public string Id { get; set; }
}

the next code doesn't work as expected:

var query = new ODataQueryBuilder()
    .For<Thing>("Things")
    .ByList()
    // expected: title,id
    // actual: Title,Id
    .Select(x => new { x.Title, x.Id });
    // allow multiple select as a solution?
    //.Select(x => x.Title)
    //.Select(x => x.Id)
    // or introduce another approach for selecting several columns?

var parts = query.ToDictionary();

We get value Title,Id for $select but expecting title,id.

The documentation talks about using .Select(s => new { s.Id, s.Sum, s.Type }).

pikami commented 1 day ago

By default, when you use new { x.Title, x.Id }, C# automatically assigns the property names based on the original names of the properties in your class, which are Title and Id. This is why you're seeing Title and Id in the output instead of the custom title and id specified by the [ODataPropertyName] attributes.

To resolve this, you'll need to explicitly rename the properties in your anonymous type to match the names you want in the output. You can do this by using this syntax:

.Select(x => new { title = x.Title, id = x.Id })

While it is possible to modify the library to automatically map the [ODataPropertyName] attribute to the names, I don’t think that would be the right call.