[英]Automapper, map Source to property of Destination
我想将对象的(源)列表映射到目标对象的属性:
class Source
{
public string Name { get; set; }
}
class Destination
{
public List<Source> ThingsWithNames { get; set; }
}
我所看到的所有问题都是相反的,但是我想在这里“放宽”我的对象。
如果我正确理解...
你在做什么
Mapper.Map<Source, Destination>(sourceList);
是真的
Mapper.Map<Source, Destination>(IList<Source> sourceList); // this is an error
您不需要为此使用AutoMapper。 相反,它只是:
var destination = new Destination();
// or if you have another entity
var destination = Mapper.Map<Destination>(someotherEntity);
destination.ThingsWithNames = sourceList;
如果someotherEntity
是包含“ Source
列表”的组合,则可以定义该映射。
Mapper.CreateMap<SomeotherEntity, Destination>()
.ForMember(d => d.ThingsWithNames, e => e.SourceList))
现在,如果您只关心Source
的Name属性,则定义一个映射
Mapper.CreateMap<Source, string>().ConvertUsing(s => s.Name);
如果需要收集,它将自动为您提供List<string>
SomeOtherEntity
List<Source> SourcesList { get; set; }
Destination
List<string> ThingsWithNames { get; set; }
var destination = Mapper.Map<Destination>(someOtherEntity);
// now destination.ThingsWithNames is a List<string> containing your Source names
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.