[英]Http POST with many to many ef core 5.0
I am an application (web API core ) I have three tables (many to many).我是一个应用程序(网络 API 核心)我有三个表(多对多)。
Tables Name:表名称:
I am trying to create an HTTP POST endpoint for many to many tables.我正在尝试为多对多表创建一个 HTTP POST 端点。 I am getting JSON data.
我正在获取 JSON 数据。 (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 JSON 数据:通过 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.我正在尝试为多对多表创建一个 HTTP POST 端点。 I am getting JSON data in the below format.
我得到以下格式的 JSON 数据。 May I know what the best way is to save data in tables using EFCore 5.0?
我可以知道使用 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首先,你必须查看这篇关于如何建立多对多关系的文章然后你可以使用ThenInclude来连接表
also you can check this article How to handle Many-To-Many in Entity Framework Core你也可以查看这篇文章How to handle Many-To-Many in Entity Framework Core
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.