自动映射器,实体框架核心和多个嵌套集合

时间:2019-02-24 17:56:53

标签: c# entity-framework automapper

我的数据库有两个表-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存储在规则表中(使用this示例)

我的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"}]]

如果我将[名称]字段更改为新值,则规则表将如下所示。

  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;
  }

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

0 个答案:

没有答案