Automapper,map Source to Destination的属性

时间:2013-06-15 22:53:02

标签: c# automapper

我想将(源)对象列表映射到目标对象的属性:

class Source
{
    public string Name { get; set; }
}

class Destination
{
    public List<Source> ThingsWithNames { get; set; }
}

我所看到的所有问题都是相反的,但我想在这里“取消”我的对象。

1 个答案:

答案 0 :(得分:0)

如果我理解正确......

你在做什么

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
相关问题