映射已使用AutoMapper映射接口集合

本文关键字:映射 接口 集合 AutoMapper | 更新日期: 2023-09-27 18:00:58

我为一些DTO提供了以下接口:

public interface IGalleryView    
{
    ICollection<IGalleryImageView> Images { get; set; }
}
public interface IGalleryImageView 
{
     // Some simple properties
}

以及以下具体类型:

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

这些是从我的EF POCO实体映射的。这些实体看起来像:

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; }
}

我在AutoMapper中映射如下:

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

然而,我得到了以下错误:

Contracts.IGalleryImageView上的以下属性无法映射:图像添加自定义映射表达式、忽略、添加自定义解析程序或修改目标类型Contracts.IGalleryImageView。上下文:映射到属性图像从Model.GalleryImage到Contracts.IGalleryImageView从System.Collections.Generic.ICollection 1[[Model.GalleryImage, Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] to System.Collections.Generic.ICollection 1映射到属性Images[[Contracts.IGalleryImageView,Contracts,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null]]从类型Model.Gallery到Contracts.IGalleryView的映射引发了类型为"AutoMapper.AutoMapperConfigurationException"的异常。

我不确定这里的问题是什么,因为我已经为转换指定了映射。我该如何解决此问题?

映射已使用AutoMapper映射接口集合

上面的代码似乎还可以,问题与层次结构无关,但需要在原始源对象和As方法中的对象之间创建映射。对于上面的Gallery映射,它将是:

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