lundi 13 juillet 2020

Designing asp.net core web api to add sub classes/specialized objects

As an exercise, I am writing a core web api that allows keeping track of a user medias. A media can be a postcard, a photo album, a recording, a book...

I would like to know what is the way to go/best practice in writing the Add (createMedia) method:

[HttpPost]
public async Task<ActionResult<bool>> Add(Media media)

My model is comprised of several specific classes representing one type of media - like Postcard, Photoalbum, recording, etc. In addition, there is a Media type - which contains shared properties among all media types:

public class Media
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public MediaType Type { get; set; }
    public bool InUse { get; set; }
    public string Date { get; set; } //yyyy-mm-dd
    public string Owner { get; set; }
}

As an example of one of the specific media types:

public class Postcard
{
    [ForeignKey("Id")]
    public int MediaId { get; set; }
    public string From { get; set; }
    public string To { get; set; }
    public string Place { get; set; }
    public string Language { get; set; }

}

I designed my EntityFramework db to consist of a 1-1 relation between Media and the relevant specific media table.

What is the best practice in writing the Add method ? Should it receive a Media object, and based on MediaType create the respective type ? I started with this approach, and had the action receive a second parameter named detailsJson, which I would parse and fill the respective object using reflection, but figured out that POST binding will not bind 2 objects.

I'm not well versed in design patterns. Should there exist as many AddBook, AddPostcard... as many media types ? I understand all models should be POCO objects, without inheritance. I read about DTOs, but does not see how it helps me here.

Aucun commentaire:

Enregistrer un commentaire