AutoMapper for a list scenario only seems to repeat mapping the first object in the list

时光毁灭记忆、已成空白 提交于 2020-02-20 16:47:46

问题


I am developing an MVC 3 application and am using AutoMapper to move data between my ViewModels and my entities. I have a scenario where I need to move data between two lists. For some strange reason, AutoMapper seems to only copy the first object from the source object and then seems to copy the same object n times over to the destination list. For example, say you have 2 lists, source contains six entity items and destination contains 0 items as it was just instantiated. The item at position source[0] get copied over to the destination and then source[0] is copied repeatedly for the same number of items there are in the source List, in this case 6. I don't understand what could be the cause of this.

Here is the AutoMapper configuration file:

public static class AutoMapperConfigurator
{
    public static void Configure()
    {
        Mapper.CreateMap<User, UserModel>();
        Mapper.CreateMap<Posting, PostingModel>();
    }
}

Here is the Global.asax file setting

protected void Application_Start()
{
    AutoMapperConfigurator.Configure();
}

Here is the location where I am calling the Map method

userSearchModel.UserList = Mapper.Map<IList<User>, IList<UserModel>>(userEntities);

回答1:


So, a suitable solution, but not what we desire when using the AutoMapper.

This problem is common when you incorrectly override the Equals method of the entity/model being mapped.

For example, if you try to map a list of the objects above, you will get just the first object from the SourceEntity.

    public class SourceEntity 
    {
         public string MyField {get; set;}         

         public override bool Equals(object obj)
         {
              return true;
         }
    }

    public class TargetEntity 
    {
          public string MyField {get; set;}  
    }

Check that the Equals method is returning true.




回答2:


For anyone else with this problem, it appears as if the documentation was not working for me. A colleague made the following suggestion:

userSearchModel.UserList = UserEvent.Select(item => Mapper.Map<User, UserListModel>(item));

It worked like a charm.



来源:https://stackoverflow.com/questions/17268362/automapper-for-a-list-scenario-only-seems-to-repeat-mapping-the-first-object-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!