Matching two elements with an automaton

In my data layer, I have a repository that can return a list of such items:

new List<Item> { new Item { Title = "Something", DetailId = 500 }, new Item { Title = "Whatever", DetailId = 501 }, } 

There is another method in the repository that can return data for these elements if a part identifier is specified:

 // repository.GetDetail(500) would return something like: new ItemDetail { Id = 500, Size = "Large" } 

Now, in my service layer, I would like to match the above list with the following:

 new List<ServiceItem> { new ServiceItem { Title = "Something", Size = "Large" }, new ServiceItem { Title = "Whatever", Size = "Medium" }, } 

Please note that I need properties from both objects in the list ( Title in this case) and from detailed objects. Is there a good way to map this to AutoMapper?

I thought about creating a profile that depends on the instance of my repository, and then AutoMapper performs detailed queries, but it looks like it is mess to let AutoMapper retrieve new data?

Is there a clean way to map two objects into one?

+4
source share
3 answers

One possibility is to wrap the Item and ItemDetail objects in a Tuple and define your map based on this Tuple. The display code will look something like this.

 Mapper.CreateMap<Tuple<Item, ItemDetail>, ServiceItem>() .ForMember(d => d.Title, opt => opt.MapFrom(s => s.Item1.Title)) .ForMember(d => d.Size, opt => opt.MapFrom(s => s.Item2.Size)); 

You will need to join the correct Item and ItemDetail yourself. If you want Automapper to also match the item with the correct ItemDetail, you will need to change the display so that Size Automapper will search and return a match size during resolution. The code will look something like this.

 Mapper.CreateMap<Item, ServiceItem>() .ForMember(d => d.Size, opt => opt.MapFrom(s => itemDetails.Where(x => s.DetailId == x.Id).First().Size)); 

This map uses the Automapper automatic function to map Item.Title to ServiceItem.Title. The map uses IEnumerable named itemDetails to find a match, but it should be possible to replace it with a database call. Now, since this type of search is something that I don’t think Autmapper was designed for, the performance may not be that large for a lot of elements. That would be something to experience.

+4
source

This blog post describes an approach for this: http://consultingblogs.emc.com/owainwragg/archive/2010/12/22/automapper-mapping-from-multiple-objects.aspx . It calls one Map () call for each input object, but at least wraps it in a helper.

+2
source

Use ValueInjecter instead of AutoMapper, it’s easy to switch between them, and ValueInjecter supports entering values ​​from several sources from the box.

 serviceItem.InjectFrom(item); serviceItem.InjectFrom(itemDetail); 

As a bonus, you do not need to do all the static mapping, as in AutoMapper

0
source

All Articles