AutoMapper Map single list on source object into two lists on destination object
-
21-06-2021 - |
Question
I'm attempting to use AutoMapper to map from a Domain-object that contains a list of objects, where I have a boolean property, that I want to use a the property that AutoMapper uses to split that list into two destinations on the destination object.
My basic domain looks like this (source)
//Domain object
public class Article
{
public bool IsActive { get; set; }
}
so my source will be an IList<Article>
My view looks like this (destination)
//DTO
public class ViewAllArticles
{
public IList<ViewArticle> ActiveArticles { get; set; }
public ILIst<ViewArticle> InactiveArticles { get; set; }
}
public class ViewArticle
{
public bool IsActive { get; set; }
}
Wanted mapping
//wanted mapping code (source to destination)
Mapper.Map<IList<Article>, ViewAllArticles>(collectionOfAllArticles)
where ActiveArticles contain only the articles with "IsActive=true", and vice-versa for InactiveArticles.
Hope one of you can help me get started doing this kind of mapping, that I would find hugely useful.
Thanks in advance.
Solution
You can do it this way
internal class StartNewDemo
{
public static void Main(string[] args)
{
Mapper.CreateMap<IList<Article>, ViewAllArticles>()
.ForMember(map => map.ActiveArticles, opt => opt.MapFrom(x => x.Where(y => y.IsActive)))
.ForMember(map => map.InactiveArticles, opt => opt.MapFrom(x => x.Where(y => !y.IsActive)));
var list = new List<Article>() { new Article { IsActive=true }, new Article { IsActive = false } };
var result = Mapper.Map<List<Article>, ViewAllArticles>( list );
}
}
OTHER TIPS
Mapper.CreateMap<IList<Article>, ViewAllArticles>()
.AfterMap( (arts , artsvm) =>
{
//var artsvm = new ViewAllArticles();
artsvm.ActiveArticles = arts.Where(a=> IsActive==true).ToList();
artsvm.InactiveArticles = arts.Where(a=> IsActive==false).ToList();
}
You could also do ConvertUsing, and the only difference is you would start out with a
new ViewAllArticles
because you will be responsible for creating it. The only reason I didn't do that here, is because I couldn't remember if ConvertUsing allows a multiline lambda, but I would actually try ConvertUsing instead and see if that works.