C# Automapper-基于数组计数,将具有数组属性的单个对象映射到N个对象
我试图将包含数组的对象映射到没有数组的对象列表中。例如: 假设我有一个对象:C# Automapper-基于数组计数,将具有数组属性的单个对象映射到N个对象,c#,automapper,C#,Automapper,我试图将包含数组的对象映射到没有数组的对象列表中。例如: 假设我有一个对象: public class SourceInformation { public decimal Id { get; set; } public Person[] People { get; set; } ... } public class Destination { public decimal Id { get; set; } public string Name { ge
public class SourceInformation {
public decimal Id { get; set; }
public Person[] People { get; set; }
...
}
public class Destination {
public decimal Id { get; set; }
public string Name { get; set; }
...
}
人员类别:
public class Person {
public string First { get; set; }
public string Last { get; set; }
public string Middle { get; set; }
}
我想映射到这个对象:
public class SourceInformation {
public decimal Id { get; set; }
public Person[] People { get; set; }
...
}
public class Destination {
public decimal Id { get; set; }
public string Name { get; set; }
...
}
但我想要的是,如果我的People
属性中有N个Person
对象,那么在映射
每个Destination
对象都应该具有相关的名称信息,但它们都具有相同的Id
属性
如何告诉Automapper 1个SourceInformation对象映射到N个目标对象?解决了这个问题。我最终创建了一个自定义转换器和配置文件 简介:
public class MapperProfile : Profile {
public MapperProfile() {
CreateMap<SourceInformation, Destination>().ForMember(....);
CreateMap<SourceInformation, IEnumerable<Destination>>().ConvertUsing<CustomConverter>();
}
}
公共类MapperProfile:Profile{
公共MapperProfile(){
CreateMap().FormMember(..);
CreateMap().ConvertUsing();
}
}
转换器:
public class CustomConverter : ITypeConverter<SourceInformation, IEnumerable<Destination>> {
public IEnumerable<Destination> Convert(SourceInformation source, IEnumerable<Destination> destination, ResolutionContext context) {
var destinations = new List<Destination>();
foreach (var person in source.People) {
var destination = context.Mapper.Map<Destination>(source);
destination.Name = NameUtilStatic.FormatName(person.Name);
destinations.Add(destination);
}
return destinations;
}
}
公共类CustomConverter:ITypeConverter{
公共IEnumerable转换(源信息源、IEnumerable目标、ResolutionContext上下文){
var destinations=新列表();
foreach(source.People中的var person){
var destination=context.Mapper.Map(源);
destination.Name=NameUtilStatic.FormatName(person.Name);
目的地。添加(目的地);
}
返回目的地;
}
}
然后只需调用映射器(我使用注入DI的映射器),就可以简单地说\u mapper.Map(源代码)代码>
您必须先加载您的个人资料。类似于:Mapper.Initialize(cfg=>{cfg.AddProfile();})代码>
在这里可以找到更多的例子:只需将源映射到目标和源作为参数就更容易了。