AutoMapper for a list scenario only seems to repea

2020-07-20 06:09发布

问题:

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.