如何使用 AutoMapper 将子对象列表转换为字符串列表或 Guid 列表

How to use AutoMapper to convert Child Object list to either list of strings or list of Guids

我试过使用自定义转换

CreateMap<ChildB, string>().ConvertUsing(src => src.Name);

但是我 运行 有时想获取上面的字符串或者有时只想获取 Guid 的场景: CreateMap<ChildB, Guid>().ConvertUsing(src => src.Id);

它似乎抛出错误,因为它总是转换名称。对象是这样的:

public class ParentA
{
 public Guid Id {get;set;}
 public string Name {get;set;}
 public ICollection<ChildB>? {get;set;}
 ...
}

public class ChildB
{
 public Guid Id {get;set;}
 public string Name {get;set;}
 ...
}
public class ParentADTO1
{
 public Guid Id {get;set;}
 public string Name {get;set;}
 public ICollection<string> ChildNames{get;set;}
 ...
}
public class ParentADTO2
{
 public Guid Id {get;set;}
 public string Name {get;set;}
 public ICollection<Guid> ChildIds {get;set;}
 ...
}

所以问题是,我可以像这样使用 CreateMap 函数吗:

CreateMap<ParentA,ParentADTO1>()
  ...
 .ForMember(ent => ent.ChildNames, opt => opt.MapFrom(???))

CreateMap<ParentA,ParentADTO2>()
  ...
 .ForMember(ent => ent.ChildIds, opt => opt.MapFrom(???))

非常感谢您的帮助!!

谢谢 乔恩

您可以像这样设置映射配置(我假设 属性 被命名为 Children):

public class ParentA
{
 public Guid Id {get;set;}
 public string Name {get;set;}
 public ICollection<ChildB> Children {get;set;}
 // ...
}

CreateMap<ParentA,ParentADTO1>()
  // ...
 .ForMember(ent => ent.ChildNames, opt => opt.MapFrom(x => x.Children.Select(y => y.Name).ToArray()))

CreateMap<ParentA,ParentADTO2>()
  // ...
 .ForMember(ent => ent.ChildIds, opt => opt.MapFrom(x => x.Children.Select(y => y.Id).ToArray()))

@Markus 的回答当然是有效的,是一个很好的解决方案。 FWIW,这是您可以使用 built-in AutoMapper's Flattening pattern 的另一种方法。只需将 Get[PropertyName] 方法添加到源 class 即可以您想要的任何方式组合子对象。这是完整的示例:

public class Parent
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Child> Children { get; set; }

    public ICollection<string> GetChildNames()
    {
        return Children.Select(x => x.Name).ToArray();
    }

    public ICollection<Guid> GetChildIds()
    {
        return Children.Select(x => x.Id).ToArray();
    }
}

public class Child
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class ParentWithChildNames
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<string> ChildNames { get; set; }
}
public class ParentWithChildIds
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Guid> ChildIds { get; set; }
}

//No need to map the member, you could use Get[PropertyName] approach to automatically map it
var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Parent, ParentWithChildIds>();
    cfg.CreateMap<Parent, ParentWithChildNames>();
});
var mapper = config.CreateMapper();