c# - 防止 Automapper 将 IEnumerable 属性转换为列表

标签 c# asp.net automapper kentico kentico-kontent

我正在尝试将模型映射到具有从 IEnumerable 继承的类型属性的 ViewModel。这些属性具有相同的类型和名称,但 Automapper 正在将源转换为通用列表,然后无法映射到目标。

这些是我要映射的类:

BasicOverview
{
   public IRichTextContent Intro { get; set; }
   ...
}

BlogOverviewViewModel
{
   public IRichTextContent Intro { get; set; }
   ...
}

以下是定义了 IRichTextContent 类型的第三方代码:

//     Represents rich text content in a form of structured data
public interface IRichTextContent : IEnumerable<IRichTextBlock>, IEnumerable
{
    //
    // Summary:
    //     List of rich text content blocks
    IEnumerable<IRichTextBlock> Blocks { get; set; }
}

我的 Automapper 配置文件:

public AutomapperProfile()
    {
        CreateMap<BasicOverview, BlogListViewModel>();
        CreateMap<BasicOverview, ReviewListViewModel>();
        CreateMap<BasicOverview, BlogOverviewViewModel>();
    }

这是我得到的错误:

An unhandled exception occurred while processing the request. InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[KenticoCloud.Delivery.IRichTextBlock]' to type 'KenticoCloud.Delivery.IRichTextContent'. lambda_method(Closure , BasicOverview , BlogOverviewViewModel , ResolutionContext )

AutoMapperMappingException: Error mapping types.

Mapping types: BasicOverview -> BlogOverviewViewModel

Type Map configuration: BasicOverview -> BlogOverviewViewModel

Destination Member: Intro lambda_method(Closure , BasicOverview , BlogOverviewViewModel , ResolutionContext )

我尝试将以下内容添加到我的 Automapper 配置文件中:

CreateMap<IEnumerable<IRichTextBlock>, IRichTextContent>()
            .ForMember(dest => dest.Blocks, m => m.MapFrom(src => src));

产生以下错误:

TypeLoadException: Method 'GetEnumerator' in type 'Proxy_KenticoCloud.Delivery.IRichTextContent_12345678_' from assembly 'AutoMapper.Proxies, Version=0.0.0.0, Culture=neutral, PublicKeyToken=abc123ef45' does not have an implementation.

最佳答案

只是为了从Lucian Bargaoanu做出答案的评论更明显。

解决方案之一是将以下映射添加到 Automapper 配置文件:

CreateMap<IRichTextContent, IRichTextContent>().ConvertUsing(s=>s);

关于c# - 防止 Automapper 将 IEnumerable 属性转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53661707/

相关文章:

c# - 如何在 Visual Studio 中更改整个解决方案的项目名称?

automapper - 自动映射器将数组属性设置为零长度数组,而不是null

c# - 自动映射自定义通用类型 - 如何?

c# - 蓝牙串行 COM 连接。 BlueSoleil 中似乎没有用于 RFCOMM 服务器的 API

c# - 与更传统的语言相比,用 F# 编写什么样的应用程序会受益?

c# - 更改服务器机器时输入字符串的格式不正确错误

c# - 使用自定义属性映射属性

c# - 如何使用 linq 表达式展平嵌套对象

c# - 字符串未被识别为有效的日期时间(有效的 UTC 格式)

asp.net - IE 8 和客户端缓存