question

AliIrfanI-6641 avatar image
0 Votes"
AliIrfanI-6641 asked DuaneArnold-0443 commented

HTTP POST many to many ef core 5.0

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();





dotnet-aspnet-core-webapidotnet-entity-framework-core
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi,AliIrfanI-6641

Here is an official doc about saving related data to db. the demo is similar to yours,so your code above is a good choice.

0 Votes 0 ·

Myself, I would never send the data as raw Json, particularly if the Json represents a EF model object. I would rather send the DTO.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5

DTOparent can have child DTO(s) that represent the EF model objects.

0 Votes 0 ·

0 Answers