0

I am having a strange issue with AutoMapper.

If I do the following

//Get my entities from EF repository
var movements = _movementRepository.AllIncluding(movement => movement.Asset, movement => movement.Job,movement => movement.Asset.MinorEquipmentType);
var model = new List<AssetMovementDetail>();
foreach (var assetMovementDetail in movements)
{
     model.Add(Mapper.Map<AssetMovementDetail>(assetMovementDetail));
}

This works perfectly and gives me the results if I expect.

If alternatively I change model to be generated like:

var model = Mapper.Map<List<AssetMovementDetail>>(movements);

The results are different and have the same total number of results but many of the results are duplicates of each other and others are missing. Am I doing something wrong? Is this not how it is supposed to work.

GraemeMiller
  • 11,973
  • 8
  • 57
  • 111

1 Answers1

1

You need to map list to list, rather than automatically getting mapping from just one list... Hence unpexpected berhaviour. To see what I mean, please take a look into this posting: Mapping Lists using Automapper

Edit

Maybe you have the same issue that was answered over there? Extra iterations in a foreach in an AutoMapper map. Please take a look, maybe it solves, or gives you some ideas?

It also maybe related to lazy (deferred) loading in your initial linq statement.

Edit 2

Here is the code from my own project that does successfully what you trying to do:

var dbResources = _db.GetResourcesForBusiness();
var vmResources = Mapper.Map<IEnumerable<DBResource>, IEnumerable<VMResource>>(dbResources);

its a bit different format for one shot deal compared to what you're using, try to use this, see if it works for you.

Hope this helps!

Community
  • 1
  • 1
Display Name
  • 4,672
  • 1
  • 33
  • 43
  • Still produces the same weirdness even if I use Mapper.Map, List>(movements); – GraemeMiller Sep 27 '12 at 13:45
  • I am using all the includes required and so it shouldn't be Lazy loading anything. I do wonder if this is a bug but it seems so fundamental it must be something I am doing that is non standard but I don't know what. Will maybe post it as an issue. – GraemeMiller Sep 27 '12 at 15:01
  • Hard to tell you what is happening in your case. I can only tell you that I personally used list to list mapping with no issues. Please look at the edit #2 for that. – Display Name Sep 27 '12 at 15:06