asp.net-core - EF Core 不会按顺序创建子实体
问题描述
我使用 JSON 字符串来创建实体。
服务器转换 json 字符串,然后将它们添加到上下文中。
调用 Context.SaveChanges() 后,数据被正确保存。
但在那之后,儿童序列被混淆了。
我不知道为什么它们没有按顺序保存。
[楷模]
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Child> Children { get; set; }
[ForeignKey("ImageFileId")] // This model is used for storing image files.
public ImageFile ImageFile { get; set; }
public int ImageFileId { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("ParentId")]
public Parent Parent { get; set; }
public int ParentId { get; set; }
}
[控制器]
[ApiController]
[Route("api")]
public class ApiController : Controller
{
[HttpPost]
public async Task<IActionResult> Create([FromForm] CreateDTO param)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
var entity = JsonSerializer.Deserialize<Parent>(param.Parent, options);
// The Parent object has children sequentially here.
_context.Parents.Add(entity);
await _context.SaveChangesAsync(); // After this, Data aren't saved sequentially in the database.
// ...
}
}
// ...
public class CreateDTO
{
public string Parent { get; set; }
public IFormFile[] Files { get; set; }
}
[发布数据]
{
parent: {
name: "Parent Name",
children: [
{
name: "Child 1"
},
{
name: "Child 2"
},
{
name: "Child 3"
},
{
name: "Child 4"
},
{
name: "Child 5"
},
{
name: "Child 6"
},
{
name: "Child 7"
},
{
name: "Child 8"
}
]
}
}
[保存的数据](在数据库中没有保存为json数据,我这里只是用json表示)
{
Parent: {
Id: 1,
Name: "Parent Name",
ImageFileId: 1,
Children: [
{
Id: 1,
Name: "Child 1",
ParentId: 1,
},
{
Id: 2,
Name: "Child 4",
ParentId: 1,
},
{
Id: 3,
Name: "Child 3",
ParentId: 1,
},
{
Id: 4,
Name: "Child 8",
ParentId: 1,
},
{
Id: 5,
Name: "Child 5",
ParentId: 1,
},
{
Id: 6,
Name: "Child 2",
ParentId: 1,
},
{
Id: 7,
Name: "Child 7",
ParentId: 1,
},
{
Id: 8,
Name: "Child 6",
ParentId: 1,
}
]
}
}
解决方案
恕我直言,保持顺序的最佳方法是将 OrderNum 字段添加到 Children
但如果你想使用 id 值保存相同的子序列,试试这个
var entity = JsonSerializer.Deserialize<Parent>(param.Parent, options);
var children=entity.Children;
entity.Children=null;
_context.Parents.Add(entity);
await _context.SaveChangesAsync();
foreach( var child in children)
{
child.ParentId=entity.Id;
_context.Children.Add(child);
await _context.SaveChangesAsync();
}
我不确定性能会下降多少,但是如果顺序更重要,您可以尝试。
推荐阅读
- python - Python - Azure SQL 慢速插入与本地数据库
- camunda - 返回上一个任务时文件变量设置为空
- laravel - 我正在尝试显示单个数据,但它显示“尝试获取非对象的属性 'id'”
- javascript - 没有公众号的带有“运行按钮”的文本编辑器
- html - 将图像定位在中心,左右两侧有内联href
- vector - 如何在 Openlayer 中使用 HERE 矢量地图?
- ios - 如何找到 Firebase Crashlytics 初始化文件路径并仔细检查它们是否有效?
- c++ - 为什么我不能在 std::unordered_set 中使用引用类型?
- sql - 在 Teradata 中插入大表性能优化
- python - Keras:找到属于 0 个类别的 0 个图像