【问题标题】:AutoMapper How do I Merge two parents into a single object & reverseAutoMapper 如何将两个父对象合并为一个对象并反转
【发布时间】:2021-06-26 23:03:39
【问题描述】:

我一直在阅读,但这似乎与 OP 没什么不同。三个对象:

parent1 和 Parent2 是 1:1 的关系。 EF 语言中的“拥有”,两者具有相同的 Id 键

public class parent1
{
    public int Id { get; set; }
    public string field1 { get; set; }
    public int field2 { get; set; }
}

public class parent2
{
    public int Id { get; set; }
    public string field3 { get; set; }
    public int field4 { get; set; }
}

public class myDTO
{
    public int Id { get; set; }
    public string field1 { get; set; }
    public int field2 { get; set; }
    public string field3 { get; set; }
    public int field4 { get; set; }
}

当 DTO 重新使用 AutoMapper 时,是否有一种简单的方法可以将这两个父级合并在一起并将它们分开?除了单独指定每个属性。

CreateMap(); CreateMap();

相当简单,但我想避免类似

Mapper.Map(source2, Mapper.Map(source))

【问题讨论】:

标签: automapper


【解决方案1】:

避免重复调用 Map 的唯一方法是将两个父类封装为一个。这是有道理的,因为 parent1 和 parent2 是 1:1,所以实际上它们代表一个对象。

public class mergedParents
{
    public int Id { get; set; }
    public string field1 { get; set; }
    public int field2 { get; set; }
    public string field3 { get; set; }
    public int field4 { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2018-04-21
    • 2017-01-17
    • 2018-02-09
    • 2021-01-18
    • 2020-05-16
    相关资源
    最近更新 更多