1

I have lists of two separate Models that I need to merge into a parent Model that is also a list. For example:

Child model 1:

public class Sweet 
{
  public int SweetLevel {get; set;}
  public bool IsSweet {get; set;}
}

Child model 2:

public class Spicy
{
  public int IsSpicy {get; set;}
  public bool SpiceLevel {get; set;}
}

Parent model that I am trying to merge child model 1&2 into.

public class FoodItem 
{
  public int SweetLevel {get; set;}
  public bool IsSweet {get; set;}
  public bool IsSpicy {get; set;}
  public int SpiceLevel {get; set;}
}

Here is how I am trying to map the list of spicy items, and the list of sweet items to the parent FoodItem.

List<Sweet> listOfSweetItems = GetListOfSweetItems();
List<Spicy> listOfSpicyItems = GetListOfSpicyItems();

// Map the Sweet items
var mappedSweetItems = Mapper.Map<List<FoodItem>>(listOfSweetItems); // this maps correctly
// Map the Spicy items
var mappedSpicyItems = Mapper.Map<List<FoodItem>>(listOfSpicyItems); // this maps correctly

These work independently, but I want to map them into the same FoodItem object at the same time so that after one iteration it would look something like:

[{
 SweetLevel: 5,
 IsSweet: true,
 SpicyLevel: 1,
 IsSpicy: false
} , ...]

How can I map my Sweet and Spicy models into the parent FoodItem model at the same time?

1
  • 2
    Mapper.Map has an overload to update an existing object. That might work for you here. Check this out Commented Mar 26, 2019 at 22:14

1 Answer 1

2

You can try something like:

Mapper.Initialize(config =>
{
     config.CreateMap<Sweet, FoodItem>()
        .ForMember(f => f.IsSpicy, o => o.Ignore())
        .ForMember(f => f.SpiceLevel, o => o.Ignore());
     config.CreateMap<Spicy, FoodItem>()
        .ForMember(f => f.IsSweet, o => o.Ignore())
        .ForMember(f => f.SweetLevel, o => o.Ignore());
});
// ...
var foodItems = Mapper.Map<List<FoodItem>>(listOfSweetItems);
foodItems = foodItems
   .Zip(listOfSpicyItems, (foodItem, spicyItem) => Mapper.Map(spicyItem, foodItem))
   .ToList();

Hope it helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.