Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to add to/update a class collection navigation property in ASP.NET Web API (or REST in general)
    primarykey
    data
    text
    <p>This is a design problem specific to a Web API project I'm working on, but it might be a question that's general to REST principles. It's also possible I'm completely overthinking this.</p> <p>I have a class in Entity Framework that has a child collection of another class:</p> <pre><code>public abstract class Tracker { [Key] public int ID { get; set; } [MaxLength(50)] public string Name { get; set; } public virtual ICollection&lt;Unit&gt; Units { get; set; } } </code></pre> <p>The Unit class looks like this:</p> <pre><code>public class Unit { [Key] public int ID { get; set; } [MaxLength(50)] public string Name { get; set; } } </code></pre> <p>I'm working on a Web API that will GET a list of trackers, and GET a list of available units, then add a particular unit to a tracker's list of units. Trackers and Units have their own API controllers and repositories and I'm trying to figure out how to modify them to support creating this association, and what the request would look like.</p> <p>Is it appropriate to update the Tracker endpoint (/Trackers/1) via PUT to add a new Unit to the list, maybe along with the existing Units? How would I handle that on the back end? I think one of the mental hurdles I have with the PUT approach is - would I include the entire child object in the request body collection property? It wouldn't make sense to, but I'm not sure how it would work otherwise. The assumption (in my case) would be that the Unit being added to the Trackers list would be one that already exists and we're just creating the association. Should I maybe use DTOs for both of these to accomplish this more simply and map them accordingly?</p> <p>Or would it make more sense to create some new joint DTO like "TrackerUnit" with a corresponding endpoint that I can add new associations to by POSTing to that endpoint (POST /TrackerUnits), then handle the processing in a new controller for it? I would think it would also need to support a DELETE to remove the items. I'm not crazy about this approach since this endpoint wouldn't correspond to any actual resources in my system, but just be used for mapping these associations.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload