0

I'd like to create an xml snippet from an entity using AutoMapper. Something along the lines of this:

public class SourceEntity
{
    public int MasterId { get; set; }
}

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<SourceEntity, XElement>()
           .ForMember(
               dest => dest.Element("Asset.ID"),
               options => options.MapFrom(x => x.MasterId));
    }
}

When I instantiate the mapper like this:

var config = new MapperConfiguration(
    cfg => { cfg.AddProfile(new MappingProfile()); }); 
var mapper = config.CreateMapper();

I get this error:

OneTimeSetUp: AutoMapper.AutoMapperConfigurationException : Custom configuration for members is only supported for top-level individual members on a type.

I'm ultimately trying to create an XElement like this:

XElement retVal = new XElement("Asset",
    new XElement("ID", src.MasterId)
);

With a .ToString() returning this:

<Asset><ID>789</ID></Asset>
Hugo Forte
  • 5,718
  • 5
  • 35
  • 44
  • The element "Asset.ID" is not a top level member. Try just "Asset" instead. – jdweng Oct 29 '20 at 02:57
  • Thanks @jdweng, I tried that already actually - should have clarified. I do need it to go one level deeper as well. I'll add some expected output to this. – Hugo Forte Oct 29 '20 at 11:52
  • I think you need to use Initialize. See : https://stackoverflow.com/questions/36398318/automapper-mapper-createmaptsource-tdestination-is-obsolete – jdweng Oct 29 '20 at 13:18
  • Not sure that's it, I'm already using a MappingProfile : Profile and then instantiating the mapper with var config = new MapperConfiguration(cfg => { cfg.AddProfile(new MappingProfile()); }); _mapper = config.CreateMapper(); – Hugo Forte Oct 29 '20 at 15:27
  • You are getting this error because you are specifying a method for destination member and this is not permitted with AutoMapper. The error message is a bit misleading in this case. Only not nested properties and fields are supported with `ForMember()`. Also, AutoMapper is a wrong tool for creating XML from objects. You should look for conversion code, making `XElement`s from objects, like [this one](https://stackoverflow.com/a/8375101/8065832). – Prolog Nov 10 '20 at 23:50

0 Answers0