Adding a custom property to an OData Child Collection

Viewed 548

I've already reviewed this link:

Adding a custom query backed Navigation Property to ODataConventionModelBuilder

as well as this link:

Adding a custom navigation property to OData Web API Controller

Neither of these really helped to answer my question however. We are building an OData service end point using ASP.Net Core with Entity Framework Core and the AspNetCore.OData libraries, which are fairly new and may have some differences or lack of support compared to older frameworks as of this writing.

I will provide a generic example of what we are trying to do and then ask my question specifically.

Setup:

  1. We have an EF Core model set up with "Owner" and "Car" objects. A one-to-many relationship exists between an Owner and his/her Cars in the model (i.e., the Owner object has a ICollection Cars { get; set; } property.) These names are arbitrary for the example, but will suffice.

  2. We have an OwnersController : ODataController with a standard

[EnableQuery]

public SingleResult<Owner> Get(int key) {...}

method to return a specific Owner.

  1. For reasons [perhaps] not pertinent to my question, we also added a method
[EnableQuery]

public IQueryable<Car> GetCars([FromODataUri] int key)
{
    return _context.Owner
        .Include(o => o.Cars)
        .Single(record => record.Id == key)
        .Cars
        .AsQueryable();
}

to the OwnerController class so that a URL such as "http://localhost:50548/odata/Owners(123)/Cars" would return the collection of cars for the specified owner.

This works well and gives us essentially the result we want:

{
    "@odata.context": "http://localhost:50548/odata/$metadata#Car",
    "value": [
        { "OwnerId": 123, "CarId": 2346, ... },
        { "OwnerId": 123, "CarId": 3543, ... },
        ...etc...
    ]
}

Question: I hate to use the term "Navigation Property" because of its existing meaning, but what we want to be able to do is add a string property to this object, containing the collection, that represents the path to navigate back to the parent Owner data element of the set:

{
    "@odata.context":  "http://localhost:50548/odata/$metadata#Car",
    "parent": "/odata/Owner(123)",  <== ADD THIS ===
    "value": [
        ...
    ]
}

Is it possible to specify something in the ODataConventionModelBuilder to do this?

We considered creating some sort of wrapper object, but don't want to to do that because we then lose the benefits of IQueryable<> and what OData can do with that.

0 Answers
Related