首页 > 解决方案 > 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;
  }

并且所有状态都已添加且未修改。现在我只需要弄清楚如何正确地做到这一点。

标签: c#entity-frameworkautomapper

解决方案


推荐阅读