2016-04-29 65 views
2

我試圖將單個對象映射到使用automapper的對象的ICollection中,示例佈局是這樣的...Automapper:將類型對象上的單個成員映射到對象的Icollection

public class BarDto { 
    public int id {get;set;} 
    public int name {get;set;} 
    public ICollection<ExampleObject> FooCollection {get;set;} 
} 

public class Bar { 
    public int id {get;set;} 
    public int name {get;set;} 
    public ExampleObject Foo {get;set;} 
} 


Mapper.CreateMap<BarDto, Bar>() 
      .ForMember(dest => dest.FooCollection, opts => opts.MapFrom(src => src.Foo)); 

有無論如何將src.foo轉換爲列表等被接受爲ICollection?

回答

3

你可以做到以下幾點:

Mapper.CreateMap<Bar, BarDto>() 
     .ForMember(dest => dest.FooCollection, opts => opts.MapFrom(src => new List<ExampleObject>() { src.Foo })); 

或者你可以實現你自己的ValueResolver<ExampleObject, List<ExampleObject>>

,並做一些事情,如:

public class ExampleResolver: ValueResolver<ExampleObject, List<ExampleObject>> 
{ 
    protected override List<ExampleObject> ResolveCore(ExampleObject source) 
    { 
     return new List<ExampleObject>() { source }; 
    } 
} 

然後:

Mapper.CreateMap<BarDto, Bar>() 
     .ForMember(dest => dest.FooCollection, opts => opts.ResolveUsing<ExampleResolver>()); 

二段ond方法通常用於更復雜的情況,但您可以選擇任何您想要的方法。

希望它有幫助。

+0

ValueResolver的作品:)乾杯,我會認爲第一個例子會工作太多,但由於某種原因倒下,可能是與對象上的更深/更深的地圖有關。 –

+0

我想這第一個例子不起作用,因爲''中類型的順序錯誤。得到修復。 – MaKCbIMKo

+0

無論如何,高興地幫助:) – MaKCbIMKo

相關問題