Search code examples
c#asp.netmappingautomapperautomapping

Automapper map from properties to classes


I'm having an issue from converting a simple class with properties to a class with properties which are also classes themselves called ProductDataField

 public class ProductDataField
    {
      
        public string Value { get; set; }

        public string Name{ get; set; }
    }

Source:

     public class ProductDetailsViewModel 
     {
        public CultureInfo Language { get; set; }

        public string SeoTitle { get; set; }

        public string SeoDescription { get; set; }

        public string SeoKeywords { get; set; }

        public string ProductFamily { get; set; }
     }

Dest:

    public class DetailsComplexViewModel 
    {
        public ProductDataField Language { get; set; }

        public ProductDataField SeoTitle { get; set; }

        public ProductDataField SeoDescription { get; set; }

        public ProductDataField SeoKeywords { get; set; }

        public ProductDataField ProductFamily { get; set; }
   }

I am trying to map the "Name" property in ProductDataField to the property name in "ProductDetailsViewModel" and the "Value" property to the value of the property.

I have tried mapping them with CreateMap but im always getting errors like

"Expression 'x => x.ProductFamily.Value' must resolve to top-level member and not any child object's properties"

Any help would be greatly appreciated


Solution

  • This is not really what AM is for and perhaps just using reflection would work better, but it can be done :)

    CreateMap<object, ProductDataField>().ConvertUsing((s,_, c)=>new ProductDataField { Value = s as string, Name = (string) c.Items["member"] });
    CreateMap<ProductDetailsViewModel, DetailsComplexViewModel>().ForAllMembers(o=>o.PreCondition((ResolutionContext c)=>(c.Items["member"] = o.DestinationMember.Name) != null));
    

    And the Map call:

    Map<DetailsComplexViewModel>(new ProductDetailsViewModel { SeoTitle = "title", SeoDescription = "descr" }, _=>{} )