Map LLBLGen entity to DTO

508 Views Asked by At

I'm trying to create a mapping between a LLBLGen Entity and a DTO using AutoMapper.

My DTO's looks as followed:

// Parent
public int Id { get; set; }
public List<Child> Children{ get; set; } // One to Many

// Child
public int Id { get; set; }
public int Parent { get; set; } // Foreign key to parent Id

The ParentEntity contains a ChildCollection with the same name as the DTO List and an Id (with other LLBL fields that need to be ignored). So when the ParentEntity gets mapped to the Parent DTO it should also map the ChildCollection to a List of Children.

This is what I got so far:

ParentEntity parentEntity = new ParentEntity(id);

AutoMapper.Mapper.CreateMap<ParentEntity, Parent>();
AutoMapper.Mapper.CreateMap<ChildCollection, List<Child>>();

var parent = AutoMapper.Mapper.Map<Parent>(parentEntity);

This results in the Id getting mapped but List has count 0.

How can I make it work?


UPDATE:

Tried the same as my previous attempt but manually mapping the List of Children also results in the same problem: Id gets mapped but List is empty.

Mapper.CreateMap<ParentEntity, Parent>()
    .ForMember(dto => dto.Children, opt => opt.MapFrom(m => m.Children));
1

There are 1 best solutions below

1
Ilya Chumakov On BEST ANSWER

This line is not helpful:

AutoMapper.Mapper.CreateMap<ChildCollection, List<Child>>();

Instead of this, you should to add explicit map class-to-class:

AutoMapper.Mapper.CreateMap<ChildEntity, Child>();

And then you should specify exact properties to map. Both properties should have List type or similar (List<ChildEntity> as source and List<Child> as destination). So, if ParentEntity and Parent classes both have Children property, you even does not have to specify:

.ForMember(dto => dto.Children, opt => opt.MapFrom(m => m.Children));

default mapping in enough:

  Mapper.CreateMap<ParentEntity, Parent>();