How to Map an object with nested icollection to a list of dto

Viewed 43
class One 
{
public Guid Id { get; set;}
public string Name { get; set;}
public string Number { get; set;}
public virtual ICollection<Two> Comments { get; set;}
}

class Two 
{
 public Guid Id { get; set;}
 public string Text { get; set; }
 public DateTime date {get; set;}
 public virtual ICollection<Three> Likes { get; set; }
}

class Three {
 public Guid Id { get; set; }
 public string EmojiName { get; set; }
}

I created dto class:

class MainDto 
{
public stirng Name { get; set;}
public stirng Text{ get; set;}
public stirng EmojiName { get; set;}
}

I need to map data from class One to MainDto, but I do not know how. I added class tmp:

class tmp {
public string Number { get; set; }
public string Text { get; set; }
public string EmojiName { get; set; }
}

And I tried use converter in mapping profile:

profile.CreateMap<One, IList<tmp>>()
.ConvertUsing(o => o.One.Comments.SelectMany(tw => tw.Likes).Select(th => new tmp
{ Name = o.Name, Text = tw.Text, EmojiName = th.EmojiName }
).ToList())

and I thought it was enough to just use the mapper to map List to List and then the result of it map to list but gets return the collection empty. is there any other way?

2 Answers

Here is a linq solution. Probably not the fastest but I think its self documenting.

List<One> ones = GetOnes();
List<MainDto> mains = ones.Select(x => {
    var comment = x.Comments.First(y => y.Id == x.Id);
    var like = comment.Likes.First(z => z.Id == x.Id);
    return new MainDto()
    {
        Name = x.Name,
        Text = comment.Text,
        EmojiName = like.EmojiName
    };
}).ToList();
CreateMap<One, IList<MainDto>>().ConvertUsing(o => o.Comments.SelectMany(tw => tw.Likes.Select(th => new MainDto() { Name = o.Name, Text = tw.Text, EmojiName = th.EmojiName, })).ToList());

You don't need "class tmp".

Related