Reputation: 1216
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?
Upvotes: 1
Views: 418
Reputation: 4219
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!
Upvotes: 2