[英]How to handle POST call with JSON having data with “parent-child” relationship using ASP.NET Web API Entity Framework?
I have a JSON which has a format as given below:我有一个 JSON,其格式如下:
{
"header": {
"source_code": "S12345"
"user_id": "987456"
},
"body":{
"source_code": "S12345",
"wrapper_list": [
{
"item_wrapper_code": "WRAP01",
"item_amount": 10,
"item_type_amount": 2,
"creation_date": 20191115,
"worker": "W001",
"workstation_no": "1"
"item_list":[
{
"item_code": "I001"
"item_id": "",
"bar_code": "123987456"
"remark": ""
},
{
"item_code": "I002"
"item_id": "",
"bar_code": "213987456"
"remark": ""
}
]
}
]
}
}
The body of the above JSON object contains data in a parent - child relationship.上述 JSON object 的主体包含父子关系中的数据。
Parent: WRAP01
Child1: Item I001
Child2: Item I002
I must be able to parse this JSON object and insert these details as rows into respective tables, ie, Parent related stuff into Parent table and Children related stuff into Child table.我必须能够解析这个 JSON object 并将这些详细信息作为行插入到相应的表中,即将父相关的内容插入父表,将子相关的内容插入子表。
I request professionals here to kindly guide me.我请求这里的专业人士来指导我。
So, parsing Json to Entity Framwork objects is bad practise.因此,将 Json 解析为实体框架对象是不好的做法。
Firstly, create data transfer objects (DTO) that will be maps to Json.首先,创建将映射到 Json 的数据传输对象 (DTO)。 It is like: RequestDto, BodyDto, WrapperDto, WrapperItemDto.它就像:RequestDto、BodyDto、WrapperDto、WrapperItemDto。
For parse it you can use something like newtonsoft, see example:https://www.newtonsoft.com/json/help/html/DeserializeObject.htm要解析它,您可以使用类似 newtonsoft 的东西,请参见示例:https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
Then you should write EntityFramework objects that will be maps to Database tables.然后您应该编写将映射到数据库表的 EntityFramework 对象。 I hope, you knows Databases theory and already reads some articles about EntityFramework and how it implements different DB relationsips.我希望,您了解数据库理论并且已经阅读了一些关于 EntityFramework 以及它如何实现不同的数据库关系的文章。 If no, so please read about it.如果没有,请阅读它。
You needs One-To-Many relationship.你需要一对多的关系。 The one-to-many relationship can be configured in the following ways.可以通过以下方式配置一对多关系。
You can use first way.您可以使用第一种方式。 Its more easy.它更容易。 So you need 2 classes: WrapperEntity, WrapperItemEntity.所以你需要 2 个类:WrapperEntity、WrapperItemEntity。
Then, you should write code that will convert WrapperDto to WrapperEntity and WrapperItemDto to WrapperItemEntity.然后,您应该编写将 WrapperDto 转换为 WrapperEntity 并将 WrapperItemDto 转换为 WrapperItemEntity 的代码。 And then save *Entity objects in database.然后将 *Entity 对象保存在数据库中。
It's a best practise for implements such logic.这是实现此类逻辑的最佳实践。 I explain it as top level.我将其解释为顶级。 For details you can google each question separately.有关详细信息,您可以单独搜索每个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.