问题
I'm creating a Web API 2 using OData v4
to provide the following HTTP verbs for my models: GET
, POST
and PUT
, which means that for each resource (model class) I can insert/update/retrieve data from the following URLs:
- /api/myResourceName
- /api/myResourceName/{id}
And for my sub-resources (the children models) I can do the same through the following URLs:
- /api/myResourceName/{id}/subresource
- /api/myResourceName/{id}/subresource/{subresourceId}
However, in order to have a sub-resource, I necessarily need to have an IEnumerable<MySubresourceModel>
in the ResourceModel
, but there are many cases in which I don't want it because it'll be visible through the "medatata url (/api/$metadata
) as a collection but I don't allow these items to be created / updated / retrieved in the actions of the "resource model" itself.
Example:
In order to have the GET /api/people/10/addresses/5
action working, I must have:
The model:
public class PersonModel
{
// Without this property the API even doesn't run
public IEnumerable<AddressModel> Addresses { get; set; }
}
OData configuration:
modelConfiguration.AddEntity<PersonModel>("people");
modelConfiguration.AddEntity<AddressModel>("addresses");
The controller:
[ODataRoutePrefix("people/{personId}/addresses")]
public class PeopleAddressesController : ODataController
{
[EnableQueryDefault]
[ODataRoute("{id}")]
public IHttpActionResult Get(int personId, int id)
{
// [...]
}
// [...]
}
But when I don't have the property Addresses
in the PersonModel
, an exception is thrown when the application starts:
System.InvalidOperationException: The path template 'people/{personId}/addresses' on the action 'Ge*' in controller 'PeopleAddresses' is not a valid OData path template. Found an unresolved path segment 'addresses' in the OData path template 'people/{personId}/addresses'.
The question is: How can I have sub-resources without having the collection property?
PS: I've already tried using OData Actions
and Functions
but that didn't work for me.
来源:https://stackoverflow.com/questions/40343559/how-to-create-a-sub-resource-using-odata-without-creating-a-collection-propert