Search code examples
restasp.net-web-api2odatanavigation-properties

WepApi 2 Odata Controller Post/Put Relationsips/Link/Refs with Switch Statement


Using OData V3(#ref) or V4(#links) with in WebApi 2+ Controller and handling relationships:

Are Switch Statements the only way?

These 2 resources for each seem to indicate the necessity of a switch case for each navigation property.

  • Entity Relations in OData V3
  • Entity Relations in OData V4

    switch (navigationProperty)
    {
        case "Supplier":
            // Note: The code for GetKeyFromUri is shown later in this topic.
            var relatedKey = Helpers.GetKeyFromUri<int>(Request, link);
            var supplier = await db.Suppliers.SingleOrDefaultAsync(f => f.Id == relatedKey);
            if (supplier == null)
            {
                return NotFound();
            }
    
            product.Supplier = supplier;
            break;
    
        default:
            return StatusCode(HttpStatusCode.NotImplemented);
    }
    

Question: Am I supposed to hard code a switch statement for each navigation property, and if so, is there a way to have this auto-magically scaffold?


Solution

  • I had the problem like this (v4), and I solved it by using the base controller example. There are 2 base controllers: for navigation (your case) and the CRUD operations - the 3th is example of usage. The code is not so clean (I have been trying to remove unnecessary details) but I think the idea is pretty clear. I do not think that it is a best way to solve this problem, but I have not found any simpler way to add and delete properties by string. I would like to know more elegant answer. Sorry for my English.