[英]Http POST with many to many ef core 5.0
我是一个应用程序(网络 API 核心)我有三个表(多对多)。
表名称:
我正在尝试为多对多表创建一个 HTTP POST 端点。 我正在获取 JSON 数据。 (见下文)
[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 数据:通过 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"
}
]
}
]
我正在尝试为多对多表创建一个 HTTP POST 端点。 我得到以下格式的 JSON 数据。 我可以知道使用 EFCore 5.0 将数据保存在表中的最佳方法是什么吗?
我做了谷歌并找到了以下解决方案。 有没有更好的方法来做到这一点?
//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();
首先,你必须查看这篇关于如何建立多对多关系的文章然后你可以使用ThenInclude来连接表
你也可以查看这篇文章How to handle Many-To-Many in Entity Framework Core
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.