Sunday, September 14, 2014

Automapper for complex type

For simple object mapping I think Automapper is fine. For example

Mapper.CreateMap() // i tried to include count here for pricing but it didn''t worked.
var products = productRepository.GetAll().ToList();
        List productModelList = new List();
        Mapper.Map,
        IEnumerable>(products, productModelList);
        return productModelList;

Now, I want to include Minimum price of the product from a list of collection in product. So I couldn't use AutoMapper and modified my changes as below. (I know we can use MapFrom for Member. However, it didn't worked initially. )

products.ForEach(product => new
       {
           var pricingCollection = product.PricingCollection.ToList();
           productModelList.Add(new ProductModel()
           {
               ProductId = product.ProductId,
               Name = product.Name,
               PriceCount = pricingCollection.Count(),
               Price = pricingCollection.Min(x => x.Price)

           });
       });


After some thoughts and search.. I found what mistake I was making in Object Mapper and modified my CreateMap. Iniitally I was not using the o.MapFrom properly for PricingCollection here


Here is my working code,


  Mapper.CreateMap()
            .ForMember(x => x.Price, o => o.MapFrom(x => x.PricingCollection.Min(y=> y.SpecialPrice)))
            .ForMember(x => x.StoresCount, o => o.MapFrom(x => x.PricingCollection.Count()));

No comments: