c# - Automapper、Entity Framework Core 和多个嵌套集合
问题描述
我的数据库有两个表 - RuleGroups 和 Rules。我的实体框架类如下:
public class RuleGroup
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Rule> Rules { get; set; }
}
public class Rule
{
[Key]
public Guid Id { get; set; }
public Guid RuleGroupId { get; set; }
public string Name { get; set; }
public ICollection<Condition> Conditions { get; set; }
[ForeignKey("RuleGroupId")]
public virtual RuleGroup RuleGroup { get; set; }
}
[NotMapped]
public class Condition
{
public Guid Id { get; set; }
public string Name { get; set; }
}
类条件未映射,因为它正在被序列化并作为 JSON 存储在规则表中(使用此示例)
我的 DTOS 如下:
public class UpdateRuleGroupDto
{
public string Name { get; set; }
public ICollection<UpdateRuleDto> Rules { get; set; }
}
public class UpdateRuleDto
{
public string Name { get; set; }
public ICollection<UpdateConditionDto> Conditions { get; set; }
}
public class UpdateConditionDto
{
public string Name { get; set; }
}
在我的 Startup.cs 我初始化 Automapper :
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap<UpdateRuleGroupDto, RuleGroup>();
cfg.CreateMap<UpdateRuleDto, Rule>();
cfg.CreateMap<UpdateConditionDto, Condition>();
}
我有一个 API 控制器端点,它接受 JSON PATCH 文档来更改存储在数据库中的数据。
public IActionResult Patch(Guid ruleGroupId, [FromBody]JsonPatchDocument<UpdateRuleGroupDto> body)
{
RuleGroup ruleGroupFromRepo = _deviceRules.GetRuleGroup(ruleGroupId);
UpdateRuleGroupDto ruleGroupToPatch = Mapper.Map<UpdateRuleGroupDto>(ruleGroupFromRepo);
// Patching logic here
Mapper.Map(ruleGroupToPatch, ruleGroupFromRepo);
context.SaveChanges();
return NoContent();
}
问题:
进行/保存更改时,规则表中的规则会更改/获取新的 GUID。
例如,假设我们在 2 个表中有这些数据。
RuleGroup Table
[Id][Name]
[ddad5cac-e5a1-4db7-8167-66a6de3b8a0c][Test]
Rule Table
[Id][RuleGroupId][Name][Condition]
[17c38ee8-4158-4ecc-b893-97786fa76e13][ddad5cac-e5a1-4db7-8167-66a6de3b8a0c][Test][[{"Name":"Test"}]]
如果我将字段 [Name] 更改为新值,规则表将如下所示。
Rule Table
[Id][RuleGroupId][Name][Condition]
[ba106de8-bcbc-4170-ba56-80fe619cd757][ddad5cac-e5a1-4db7-8167-66a6de3b8a0c][Test2][[{"Name":"Test"}]]
请注意,[Id] 字段现在有一个新的 GUID。
编辑
@Gert Arnold 让我意识到我没有附加实体。我运行了以下代码:
foreach (var item in ruleGroupFromRepo.rules)
{
var x = _context.Entry(item).State;
}
并且所有状态都已添加且未修改。现在我只需要弄清楚如何正确地做到这一点。
解决方案
推荐阅读
- rust - 闭包可以返回对其拥有的数据的引用吗?
- spring-boot - 热插拔不适用于 IntelliJ 中的 Spring Boot
- javascript - 对 Places 服务的所有请求都必须使用 https:// 协议,并包含 API 密钥
- wordpress-theming - 木材:如何在 archive.php 中查询单个自定义帖子类型的帖子
- r - 如何/在哪里将 tidycensus 变量与人口普查局变量匹配?
- android - “损坏的工具链:无法在 buildozer 中链接简单的 C 程序?” 尝试使用 kivy buildozer 制作 android 应用程序时
- api - 如何从命令行使用 curl 对 Akamai 源进行 API 调用
- .net - OpenIDConnect .Net 框架中的多租户
- git - 如何进行向后端口变基?
- jquery - 计算 Jquery 中的具体日期是哪一天?