li-raz
li-raz

Reputation: 1696

WebAPI - odata service adding ForeignKey

i am building my the model using ODataModelBuilder, i am trying to create navigation property however in the metadata i dont see any foreginkey indication, in my solution i am not using EF, so there is no foreignKey attribute, is it possible to add it by code?

Upvotes: 0

Views: 1742

Answers (1)

Jen S
Jen S

Reputation: 4555

As you clarified in your comment, the reason you want to add foreign key information is because your client application is not including related entities when you query the main entity. I don't think foreign keys are the problem here.

As an example, I'll use two entity types: Customer and Order. Every Customer has some number of associated Orders, so I have a navigation property on Customer called Orders that points to a collection of Orders. If I issue a GET request to /MyService.svc/Customers(1), the server will respond with all of the Customer's information as well as URLs that point to the related Order entities*. I won't, by default, get the data of each related Order within the same payload.

If you want a request to Customers(1) to include all of the data of its associated Orders, you would add the $expand query option to the request URI: /MyService.svc/Customers(1)?$expand=Orders. Using the WCF Data Services client (DataServiceContext), you can do this with .Expand():

DataServiceQuery<Customer> query = context.Customers.Expand("Orders");

However, WebAPI OData doesn't currently support $expand (the latest nightly builds do though, so this will change soon).

The other approach would be to make a separate request to fill in the missing Order data. You can use the LoadProperty() method to do this:

context.LoadProperty(customer, "Orders");

The LoadProperty approach should work with WebAPI as it stands today.

I know this doesn't answer your original question, but I hope addresses your intent.

*In JSON, which is the default format for WebAPI OData services, no links will show up on the wire, but they are still there "in spirit". The client is expected to be able to compute them on its own, which the WCF Data Services Client does.

Upvotes: 2

Related Questions