开发者

Issue with AutoMapper and mapping IEnumerable collections

开发者 https://www.devze.com 2023-01-14 15:13 出处:网络
Here is the code for the mapper: public IEnumerable<GetQuestionsContract> Map(IEnumerable<XmlNode> nodes, XmlNamespaceManager namespaceManager)

Here is the code for the mapper:

public IEnumerable<GetQuestionsContract> Map(IEnumerable<XmlNode> nodes, XmlNamespaceManager namespaceManager)
    {
        Mapper.CreateMap<XmlNode, GetQuestionsContract>()
            .ForMember(
                dest => dest.Id, 
                options =>
                options.ResolveUsing<XmlNodeResolver<string>>().FromMember(
                    source => source.SelectSingleNode("//wfauth60xsd:questionID", namespaceManager)))
            .ForMember(
                dest => dest.Question, 
                options =>
                options.ResolveUsing<XmlNodeResolver<string>>().FromMember(
                    source => source.SelectSingleNode("//wfauth60xsd:question", namespaceManager)));

        return Mapper.Map<IEnumerable<XmlNode>, List<GetQuestionsContract>>(nodes);
    }

While this works, it only appears to return the first element in the IEnumerable list multiple times (as many times as their are items in the XmlNodeList).

Update: I've simplified the code and update the title. The scenario works just fine if I'm mapping to one XmlNode, but the Enumeration seems to be an issue. For example, the following code works just fine:

public SomeIdContract Map(XmlDocument document, XmlNamespaceManager namespaceManager)
    {
        Mapper.CreateMa开发者_开发技巧p<XmlDocument, SomeIdContract>()
            .ForMember(
                dest => dest.Id, 
                options =>
                options.ResolveUsing<XmlNodeResolver<string>>().FromMember(
                    source => source.SelectSingleNode("//wfauth60msgs:someID", namespaceManager)));

        return Mapper.Map<XmlDocument, SomeIdContract>(document);
    }

Any thoughts? Thanks!


I had the exact same problem. Turns out AutoMapper was using my model object's Id (Guid) property (which is normally privately set by nhiberate) as an identifier when caching the source (no matter what other properties differed). During testing I never set the id, so the default guid was the same for all objects, which explained why only the first item in the IEnumerable was returned for all. So I had to make Id public to my tests, set the Id for each item and then everything worked.


It appears that the issue is not with AutoMapper, rather with XPath selecting the first node for some crazy reason.

Converting the XmlDocument to an XDocument and using Linq-to-Xml solved my issue.

Thanks for the input.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号