使用 AutoMapper 映射 Parent/Child 接口属性

Map Parent/Child Interface Properties using AutoMapper

我在标准层次结构中使用了以下接口和 DTO:

public interface IPageView {
    IPageView Parent { get; set; }
    ICollection<IPageView> Children { get; set; }
}

这是使用以下具体实现的class:

public class PageView : IPageView {
    IPageView Parent { get; set; }
    ICollection<IPageView> Children { get; set; }
}

为简洁起见,我省略了其他属性和构造函数。我正在使用 Automapper 从我的 Page EF POCO 实体映射到具有以下内容的接口 DTO:

AutoMapper.Mapper.CreateMap<Page, IPageView>().As<PageView>();

当 AutoMapper 尝试创建地图时,出现以下异常:

The following property on Pipeline.CMS.Contracts.UI.IPageView cannot be mapped: Pages Add a custom mapping expression, ignore, add a custom resolver, or modify the destination type Pipeline.CMS.Contracts.UI.IPageView. Context: Mapping to property Pages from Model.Page to Interfaces.IPageView Mapping to property Pages from System.Collections.Generic.ICollection1[[Model.Page,Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] to System.Collections.Generic.ICollection1[[Interfaces.IPageView, Interfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] Mapping from type ModelPage to Interfaces.IPageView Exception of type 'AutoMapper.AutoMapperConfigurationException' was thrown.

显然这是因为 AutoMapper 无法映射 IPageView,因为它还没有被映射!

我的问题是如何解决这个问题?我不介意在 AutoMapper 配置中指定一个具体的 class。

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

AutoMapper.Mapper.CreateMap<Page, PageView>(); // Additional line here needed
AutoMapper.Mapper.CreateMap<Page, IPageView>().As<PageView>();