简体   繁体   中英

Http POST with 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. I am getting JSON data. (see below)

[HttpPost()]
public async Task<IActionResult> CreateBook([FromBody] List<Entities.Book> bookCollection)
{
   HERE: I WOULD LIKE TO ADD RECORDS TO THE BOOK TABLE FOR EXAMPLE “MathBook” and “ScienceBook”. 
 Also, would like to add records to BookCategory(linking table)
//Assuming category already exists 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 the below format. May I know what the best way is to save data in tables using EFCore 5.0?

I did google and found the 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();

First, you must check this article on how to make many-to-many relationships Then you can use ThenInclude to join tables

also you can check this article How to handle Many-To-Many in Entity Framework Core

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM