Sailing Judo
Sailing Judo

Reputation: 11243

Proper way to Get related records from ASP.Net Web API?

I have a many-to-many relationship between two classes: Vendors and Products.

In my Web API I have a controller for each class. Both controllers have the obvious actions that Get a list of the objects and Get a single object by Id.

What I need is an action that Gets the many objects for each of the objects. For example, if I provide a VendorId then I want all the Products that Vendor supplies. Likewise, if I provide the ProductId then I wants all the Vendors that supply the Product.

I have three questions:

1) I think the Product controller should have the action that takes a VendorId and returns the Products (and visa-versa for the Vendor controller). Is this the "proper" approach?

2) How do I implement the above? I can't just add another Get action that takes an Id because the controllers already have an action with that method signature (the single item method).

For example:

http://localhost:53962/api/product/1         // grabs product with Id = 1.
http://localhost:53962/api/product/vendor/1  // causes 404

3) What should the Url look like when I want all the Products for a specific vendor?

Upvotes: 0

Views: 136

Answers (1)

Maggie Ying
Maggie Ying

Reputation: 10175

1) I think the Product controller should have the action that takes a VendorId and returns the Products (and visa-versa for the Vendor controller). Is this the "proper" approach?

Yes, this will work. For example, you can have 2 such actions in your ProductController:

    public Product Get(int id) {...}
    public Product GetProductWithVendorId(int vendorId) {...}

2) How do I implement the above? I can't just add another Get action that takes an Id because the controllers already have an action with that method signature (the single item method).

That is correct if you want to call the above 2 actions using route parameter. There are different ways to approach this. One way is to modify your route. Another way is to pass the action parameter in the URL.

3) What should the Url look like when I want all the Products for a specific vendor?

Here is an example of passing parameter in the URL. This URL will invoke the ProductController's 'Get' action:

http://../api/product/123

This URL will invoke the ProductController's 'GetProductWithVendorId' action:

http://../api/product?vendorid=456

Upvotes: 1

Related Questions