For my ASP.NET Web API, I have a many-to-many relationship similar to this:
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
public ICollection<BookTag> BookTags { get; set; }
}
public class BookTag
{
public int TagId { get; set; }
public Tag Tag { get; set; }
public int BookId { get; set; }
public Book Book { get; set; }
}
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<BookTag> BookTags { get; set; }
}
Now I created DTOs and controllers for all 3 but this means:
I can't create a Tag
when creating a Book
. I have to create the Book
first and then after make POST
request to BookTags
by passing both the TagId
and BookId
.
I have a POST Dto for Book
but I'm unsure what to put in there. I am able to get the BookTags
through the response in a Book
.
I now have to create 3 controllers which is a pain along with the repositories, DTOs etc. (flexible but more stuff to maintain)
Is it best practice to have it like this? I don't mind the approach but would like to know if there is any easier way to associate books with tags.
I am hoping for an easier way to maintain this relationship and possibly make a POST
request simpler to add tags
I dont think there is any issue in creating a Tag
or a Book
Separately. The relationship between them is maintained in BookTag
table (which makes them independent from each other).
The approach you have used here to handle the many to many relationship is pretty common and used often to handle it.