开发者

How to configure AutoMapper to flatten a 1:n relation?

Consider two entity classes CD and Track:

public class CD
{
    public long Id {get; set;}
    public string Name {get; set;}
    public IList<Track> Tracks {get; set;}
}

public class Track
{
  开发者_开发技巧  public long Id {get; set;}
    public string Name {get; set;}
    public CD CD {get; set;}
}

And consider the CDTrackModel:

public class CDTrackModel
{
    public long CdId {get; set;}
    public string CdName {get; set;}
    public long TrackId {get; set;}
    public string TrackName {get; set;}
}

And the GUI should be like the red table:

How to configure AutoMapper to flatten a 1:n relation?

Automapper mappings:

Mapper.CreateMap<CD, CDTrackModel>()
.ForMember(vm => vm.CDId, o => o.MapFrom(m => m.Id)
.ForMember(vm => vm.CDName, o => o.MapFrom(m => m.Name)
// How to map the Tracks ???
;

Is it possible to create the required mapping using AutoMapper ?


The suggestion from Jimmy points me in the right direction...

Why not just map the Track Entity to the CDTrackModel instead of mapping the CD entity to the CDTrackModel?

The code would be:

Mapper.CreateMap<Track, CDTrackModel>()
.ForMember(vm => vm.TrackId, o => o.MapFrom(m => m.Id)
.ForMember(vm => vm.TrackName, o => o.MapFrom(m => m.Name)
.ForMember(vm => vm.CDId, o => o.MapFrom(m => m.CD.Id)
.ForMember(vm => vm.CDName, o => o.MapFrom(m => m.CD.Name)
;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜