Search code examples
c#linqautomapper

Automapper - Set collection items field in the current context


I'm trying to map an Enumerable collection of items from class Source to an Enumerable collection of Destination class obj. Class Destination derives from Class Source, and it differs only for a boolean property.

public class Source
{
 public string ID {get;set;}
 public string Color {get;set:}
}

public class Destination : Source
{
 public bool IsDefault {get;set;}
}

I have a container class as follows:

public class Container
{
  public string DeafultID {get;set;}
  public Enumerable<Source> SourceCollection {get;set}
}

I want to map the SourceCollection property of Container class to a Enumerable collection, where IsDefault is true only for the single element with ID == DefaultID.

Something like:

var container = Contailer.Build();

var newCollection = automapper.Map<IEnumerable<Source>, IEnumerable<Destination>>(container.SourceCollection)
.something(destinationItem.IsDefault = (sourceItem.ID == DefaultID));


Solution

  • For a more readable solution, I suggest you to proceed element by element projecting through a select the entire collection, handling the property in that context.

    var myCollection = container.SourceCollection.Select(item => MapSingleItem(item, cointainer.DefaultId);
    
    private Destination MapSingleItem(Source item, string defaultId)
    {
        var mappedItem = _mapper.Map<Source, Destination>(item);
        mappedItem.IsDefault = (mappedItem.ID == defaultId);
    
        return mappedItem;
    }