Automapper failing to map on IEnumerable

2019-03-10 13:31发布

问题:

I have two classes like so:

public class SentEmailAttachment : ISentEmailAttachment
{
    public SentEmailAttachment();

    public string FileName { get; set; }
    public string ID { get; set; }
    public string SentEmailID { get; set; }
    public string StorageService { get; set; }
    public string StorageServiceFileID { get; set; }
}

And

public class SentEmailAttachmentItem : ISentEmailAttachment
{
    [ItemName]
    public string ID { get; set; }
    public string SentEmailID { get; set; }
    public string FileName { get; set; }
    public string StorageService { get; set; }
    public string StorageServiceFileID { get; set; }
}

Identical, as you can see (they both implement interface to ensure this)

I then have the following mapping:

Mapper.CreateMap<IEnumerable<SentEmailAttachmentItem>, IEnumerable<SentEmailAttachment>>();
Mapper.CreateMap<IEnumerable<SentEmailAttachment>, IEnumerable<SentEmailAttachmentItem>>();

I then have the following Unit test:

//create a load of sent email attachments
var listOfSentEmailAttachments = new List<SentEmailAttachment>();

for (int i = 0; i < 10; i++)
    listOfSentEmailAttachments.Add(new SentEmailAttachment { FileName = "testFileName", ID = Guid.NewGuid().ToString(), SentEmailID = Guid.NewGuid().ToString(), StorageService = "S3", StorageServiceFileID = "SomeFileID" });

var sentEmailAttachmentItems = Mapper.DynamicMap<IEnumerable<SentEmailAttachment>, IEnumerable<SentEmailAttachmentItem>>(listOfSentEmailAttachments);

var itemToTest = sentEmailAttachmentItems.First();

Assert.IsInstanceOfType(itemToTest, typeof(SentEmailAttachmentItem));

This fails - The IEnumerable sentEmailAttachmentItems is empty. It didn't map the list of SentEmailAttachments to it...

Any idea what's going on??

I have it working on single objects (mapping one of each to one of each) but not a collection...

回答1:

You do not need to explicitly map collection types, only the item types. Just do:

Mapper.CreateMap<SentEmailAttachment, SentEmailAttachmentItem>();
var attachments = Mapper.Map<IEnumerable<SentEmailAttachment>, List<SentEmailAttachmentItem>>(someList);

That will work just fine.



回答2:

EDIT: I found an easy way to use DynamicMap with collections.

IEnumerable<FakeItem> unmappedItems = Repository.GetItems();
IEnumerable<MappedItem> mappedItems = unmappedItems.Select(Mapper.DynamicMap<MappedItem>);

— Original message —

The way Jimmy says to use it works, but I try to use DynamicMap when I can to avoid having to do "CreateMap" for every mapping I need. I don't think DynamicMap works with collections very well, if at all. It does not throw an exception, but the result is an empty set.

From testing over the past couple of days, you cannot use DynamicMap for collections at this time (that I know of).



标签: c# AutoMapper