GraemeMiller
GraemeMiller

Reputation: 12273

Why do I get odd AutoMapped results if I map directly from IEnumerable to IEnumerable?

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.

Upvotes: 0

Views: 97

Answers (1)

Display Name
Display Name

Reputation: 4732

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!

Upvotes: 1

Related Questions