HTTP POST many to many ef core 5.0

Ali, Irfan I 1 Reputation point
2021-06-01T13:49:50.187+00:00

I am an application (web API core ) I have three tables (many to many).

Tables Name:
• Book (BookId, Name)
• Category (CategoryId, CategoryName)
• BookCategory (BookId, CategoryId)

I am trying to create an HTTP POST endpoint for many to many tables.

[HttpPost()]
public async Task<IActionResult> CreateBook([FromBody] List<Entities.Book> bookCollection)
{
   **HERE: I WOULD LIKE TO ADD A RECORDS TO THE BOOK TABLE FOR EXAMPLE “MathBook” and “ScienceBook”. Also, would like to add records to BookCategory(linking table)
//Assuming category already exist in the Category table.** 
}

JSON Data: Passing via POSTMAN

[
  {
    "BookId": "9a6383b7-f581-405f-9cd4-4adf91052ca6",
    "name": "MathBook",
    "category": [
      {
        "CategoryId": "2329E0D5-476F-407A-9458-949D0D08123F"
      },
      {
        "CategoryId": "2325E0D5-476F-407A-9458-949D0D08123F"
      }
    ]
  },
  {
    " BookId": "4a6383b7-f581-405f-9cd4-4adf91052ca6",
    "name": "ScienceBook",
    "category": [
      {
        "CategoryId": "3329E0D5-476F-407A-9458-949D0D08123F"
      },
      {
        "CategoryId": "3329H0D5-476F-407A-9458-949D0D08123F"
      }
    ]
  }
]

I am trying to create an HTTP POST endpoint for many to many tables. I am getting JSON data in a below format. May I know what the best way is to save data in tables using EFCore 5.0.

I did google and found below solution. Is there any better way to do this?

//Get bookCategory from the table
var category = context. Category.where(c=>c. CategoryId== categoryId)

//Create Book Object
 var MathBook = new Book()
  {
       Title = "MathBook",
       Genres = category
  };
context.AddRange(MathBook);
context.SaveChanges();
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
696 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,188 questions
{count} votes