1
votes

I have the following interfaces for some DTOs:

public interface IGalleryView    
{
    ICollection<IGalleryImageView> Images { get; set; }
}

public interface IGalleryImageView 
{
     // Some simple properties
}

and the following concrete types:

public class GalleryView : IGalleryView 
{
    public GalleryView() {
        Images = new List<IGalleryImageView>();
    } 
    public ICollection<IGalleryImageView> Images { get; set; }
}

public class GalleryImageView : IGalleryImageView 
{
}

These are being mapped from my EF POCO Entities. These entities look like:

public partial class Gallery {
    // Constructors removed for brevity
    public virtual ICollection<GalleryImage> Images { get; set; }
}

public partial class GalleryImage {
    public virtual Gallery Gallery { get; set; }
}

I am mapping these in AutoMapper as follows:

AutoMapper.Mapper.CreateMap<GalleryImage, IGalleryImageView>()
            .As<GalleryImageView>();

AutoMapper.Mapper.CreateMap<Gallery, IGalleryView>()
            .As<GalleryView>();

However, I am getting the following error:

The following property on Contracts.IGalleryImageView cannot be mapped: Images Add a custom mapping expression, ignore, add a custom resolver, or modify the destination type Contracts.IGalleryImageView. Context: Mapping to property Images from Model.GalleryImage to Contracts.IGalleryImageView Mapping to property Images from System.Collections.Generic.ICollection1[[Model.GalleryImage, Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] to System.Collections.Generic.ICollection1[[Contracts.IGalleryImageView, Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] Mapping from type Model.Gallery to Contracts.IGalleryView Exception of type 'AutoMapper.AutoMapperConfigurationException' was thrown.

I'm not sure what the issue is here, as I have specified maps for the conversion. How can I resolve this?

1
Is there any relevant code missing? I added the code from above to a test project, and do not get an exception calling Mapper.Map. - tgriffin

1 Answers

0
votes

It seems that the above code is OK and the problem isn't related to the hierarchy, BUT a map needs to be created between the original source object and the object in the As method. For the Gallery mapping above, it would be:

AutoMapper.Mapper.CreateMap<Gallery, GalleryView>(); // Additional line here needed
AutoMapper.Mapper.CreateMap<GalleryView, IGalleryViewView>().As<GalleryViewView>();