Include related entities with WebAPI OData request

2019-05-10 22:36发布

问题:

Is there any way to include related entities in an OData request?

For example, I have a Person entity and a Task entity. The relationship is one-to-many, with a Person having many Tasks. If I query the data with the OData request:

/odata/Person

to get all the Person entities, the json returned does not include a Tasks property for each Person.

However, if I query the data with the OData request:

/odata/Person(14)/Tasks

I get the collection of Tasks that belong to that Person.

What I'm hoping to be able to do is get ALL of the Tasks for all of the Person entities when I make my /odata/Person request.

回答1:

Try

/odata/Person?$expand=Tasks

it will expand the navigation property "Tasks" in each entity person. If you want to only query Tasks, do not need other properties, you can try:

/odata/Person?$select=Tasks&$expand=Tasks

PS: Your service need to support $expand and $select.