I am using a client to call an API. In the API - I want the model to populate from the request body - but I want the model to be structured differently depending upon the name of a single property. Basically I want to create something like a switch/case scenario with a data model, but am unsure how to implement this. The last model contains pseudo code based upon what I want to acheive (obviously generic type won't work in the way I described, but I feel it completes my example). Here's my example:
Controller:
[HttpPost("customer", Name = "Submit Customer")]
public IActionResult ActivateCustomer([FromBody]Customer customer)
{
//Do something with the Customer object.
return Ok();
}
Customer Model:
public class Customer
{
public CustomerInfo customerInfo { get; set; }
public SponserInfo sponserInfo { get; set; }
}
CustomerInfo:
public class CustomerInfo
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
//etc.
}
SponserA:
public class SponserA
{
public int ReferenceId { get; set; }
public string Password { get; set; }
}
SponserB:
public class SponserB
{
public string UserName{ get; set; }
public string Relation { get; set; }
public string Department { get; set; }
}
SponserInfo: (pseudo-code of what I would like)
public class SponserInfo
{
public string SponserName { get; set; }
public T SponserInfo { get; set; }
switch(this.SponserName)
{
case "Sponser A's Name":
T = SponserA;
break;
case "Sponser B's Name":
T = SponserB;
break;
}
}
Here's one extensible way.
An attribute maps the sponsor name to the subclass, so SponsorInfo doesn't have to be aware of all subclasses.
It uses an abstract base class (
Sponsor
) for all Sponsor types (as also recommended by @Flydog57).When
SponsorInfo.SponsorName
is assigned, the instance of a subclass of this is created (so you have to assignSponsorName
first).You can adjust that depending on how you actually map the properties from your model.
This is dual licensed as public domain (CC0) and the normal licensing of Stack Overflow.