Question

I have created OData service for a relational table. I am trying to figure out how my post query will look like when posting to tables that has foreign key relation and also to reduce number of calls.

Example tables are:

Person

  • PersonID
  • Name
  • EmailAddress

Residence

  • ResidenceID
  • PersonID
  • Address

In order to create new entry into residence table, typically I will find out the PersonID based on the name or email address and then insert into Residence table.

How can I accomplish the same using my OData JSON api with single call? Is it possible? I am using fiddler to test the service.

Thanks in advance.

-ap

Was it helpful?

Solution

In general, there's not a really good way to do this in OData - but don't stop reading, I'll explain why and provide a few suggestions.

The reason you should think twice about doing this in production is because of the fragility of the insert process. What happens if you have two people in the database with the same name? What if there's nobody with that name? What if you misspelled the name? Would you throw an HTTP error for duplicates? Would they have to retry the insert? <- In essence, there are a ton of questions that arise because the user didn't actually pick a particular record for binding to the new record. This process is greatly simplified if you select the Person up front and just insert the new Residence with a binding to the PersonID. In the new JSON format for OData, that would look something like this:

{
    "odata.type": "My.User",
    "ReferredBy@odata.bind": "http://.../MyService.svc/Users('haoche')",
    "BillingAddress": {
        "odata.type": "My.Address",
        "City": "Clinton",
        "Line1": "23456 Cleveland St",
        "Line2": null,
        "State": "TX",
        "ZipCode": "98052"
    },
    "DisplayName": "David Hamilton",
    "FavoriteTags": [],
    "JoinedAt": "2012-10-05T14:14:43.1229977-07:00",
    "LastSeenAt": "2012-10-05T14:14:43.1269991-07:00",
    "UserID": "davham"
}

That "ReferredBy@odata.bind" is where you put the ID of the person you're linking to. If you're not using the new OData format, the payload would look like this (see example 2). Shameless plug: this is why you should be using the new JSON format :).

So the primary suggestion I have is that I would really, strongly recommend that you have users look up the data first rather than trying to combine two operations into one. If, however, you're really set on having one operation, you could do so with a service operation or an action, depending on what version of OData you're using.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top