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.
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 );
}
}