加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 防止Automapper将IEnumerable属性转换为List

发布时间:2020-12-15 22:54:31 所属栏目:百科 来源:网络整理
导读:我正在尝试将Model映射到ViewModel,该ViewModel具有从IEnumerable继承的类型属性.属性具有相同的类型和名称,但Automapper将源转换为通用列表,然后无法映射到目标. 这些是我想要映射的类: BasicOverview{ public IRichTextContent Intro { get; set; } ...}B
我正在尝试将Model映射到ViewModel,该ViewModel具有从IEnumerable继承的类型属性.属性具有相同的类型和名称,但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,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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读