加入ICollection表时自动执行“错误映射类型”错误

问题描述 投票:0回答:1

在基于ASP.NET MVC和EF的Angular项目中,我有以下实体,如下所示:

注意:如果我不添加文件附件,则没有错误。但是在映射期间添加导致此错误的文件。

Ticket.cs:

public class Ticket
{
    [Key]
    public int Id { get; set; }

    public string Summary { get; set; }

    public string Description { get; set; }

    //code omitted for brevity 

    public virtual ICollection<FileAttachment> FileAttachments { get; set; }
}

TicketViewModel.cs:

public class TicketViewModel
{
    public int Id { get; set; }

    //code omitted for brevity 

    public virtual ICollection<FileAttachmentViewModel> FileAttachments { get; set; }
}

FileAttachmentViewModel.cs:

public class FileAttachmentViewModel
{
    public int Id { get; set; }

    public int TicketId { get; set; }

    public string FileName { get; set; }

    public byte[] FileData { get; set; }

    //code omitted for brevity 

    public virtual Ticket Ticket { get; set; }
}

这是映射和Save方法,我遇到“错误映射类型。映射类型:TicketViewModel - > Ticket ...”错误。

Service.cs:

public TicketViewModel Save(TicketViewModel model)
{
    //here I encounter the error while mapping TicketViewModel to Ticket
    var record = model.MapEntity<Ticket>();

    //code omitted for brevity 
}

Mapping.cs:

CreateMap<Ticket, TicketViewModel>();    
CreateMap<TicketViewModel, Ticket>()
    .ForMember(dest => dest.FileAttachments, opts => opts.MapFrom(src => src.FileAttachments);


CreateMap<FileAttachment, FileAttachmentViewModel>();
CreateMap<FileAttachmentViewModel, FileAttachment>();

任何帮助,将不胜感激...

asp.net asp.net-mvc angular entity-framework automapper
1个回答
0
投票

有助于您的Ticket类的定义至少具有自己的属性FileAttachments的定义。它可能与您的FileAttachments属性类型是接口这一事实有关。您没有FileAttachmentViewModel类型的任何映射,这是将一个通用集合映射到另一个集合的要求。我假设你有一个FileAttachment类型的属性,而不是Ticket类中的FileAttachmentViewModel。因此AutoMapper会给你一个例外。

© www.soinside.com 2019 - 2024. All rights reserved.