简体   繁体   中英

How to use AutoMapper to map from single value to a collection?

I have a source class of

public class SourcePerson {
    public Ethnicity Ethnicity { get; set; }
}
public enum Ethnicity {}

and I need to map that to a destination class of

public class DestinationPerson {
    public EthnicityType[] Ethnicities { get; set; }
}
public enum EthnicityType {}

How would I configure that in AutoMapper? The documentation mentions mapping from one collection to another, but not from a scalar to a collection (unless I missed it).

To be absolutely explicit: I have a source XSD file with this:

<xs:element name="Ethnicity" type="Ethnicity" minOccurs="1" maxOccurs="1" />

And I have a destination XSD file with this:

<xs:element name="Ethnicities" maxOccurs="1" minOccurs="1">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="Ethnicity" type="EthnicityType" minOccurs="1" maxOccurs="5" />
        </xs:sequence>
    </xs:complexType>
</xs:element>

I've used the xsd.exe tool to automatically generate C# classes from these XSD files. Now, when I deserialize an XML file that conforms to the source XSD, I get classes generated for that source XSD. I need to AutoMapper that into the classes generated for the destination XSD.

I don't have a ton of experience with AutoMapper, but I know I've mapped a result set into a collection before, and I think I did it in a way similar to this:

CreateMap<Foo, FooDto>().ReverseMap();
var foos = mapper.Map<IEnumerable<Foo>>(fooDtos);

That is, AutoMapper was able to generate a collection of objects for me based on another collection I got as a result set from a Web API call.

I suppose if it's not able to go 1 to Many in the mapping you could always just add your single Ethnicity object to a collection before mapping, could you not?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM