0

我有一个非常奇怪的错误,我无法理解。我正在使用 AutoMapper 6AutoMapper.CollectionAutoMapper.Collection.EntityFramework.

https://github.com/AutoMapper/AutoMapper.Collection

从下面的屏幕截图中可以看出,除了 Image 为 null 之外,每个组件都进行了更新updatedContact。但是,如果我只为updatedImage它做一个显式映射。它还可以毫无问题地更新图像集合。有没有人经历过这个?其他单个属性也可以,但由于某种原因Image会造成麻烦。

//Works
var updatedArticle = Mapper.Map<ArticleViewModel, Article>(articleVm, articleOriginal);
//Every component is updated a part from Image.
var updatedContact = Mapper.Map<ContactViewModel, Contact>(contactVm, contactOriginal);
//Works
var updatedImage = Mapper.Map<ImageViewModel, Image>(contactVm.Image);
//Works
var newContact = Mapper.Map<ContactViewModel, Contact>(contactVm);

在此处输入图像描述

映射:

cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
    .EqualityComparison((src, dst) => src.Id == dst.Id);

cfg.CreateMap<ImageViewModel, Image>(MemberList.Source)
    .EqualityComparison((src, dst) => src.Id == dst.Id)
    .ForSourceMember(x => x.IsDeleted, opt => opt.Ignore())
    .ForMember(dest => dest.ImageBytes, opt => opt.MapFrom(src => Encoding.ASCII.GetBytes(src.Image)));

cfg.CreateMap<ContactViewModel, Contact>(MemberList.Source)
.EqualityComparison((src, dst) => src.Id == dst.Id)
.ForSourceMember(x => x.IsDeleted, opt => opt.Ignore())
.ForSourceMember(x => x.FullName, opt => opt.Ignore());

文件:

public class ArticleViewModel
{
    public int Id { get; set; }
    ... 
    public List<ImageViewModel> Images { get; set; }
}

public class Article : IEntity<int>
{
    public int Id { get; set; }
    ...
    public virtual ICollection<Image> Images { get; set; }  
}

public class ContactViewModel
{
    public int Id { get; set; }
    ... 
    public ImageViewModel Image { get; set; }
}

public class Contact: IEntity<int>
{
    [Key]
    public int Id { get; set; }

    ...

    public int? ImageId { get; set; }

    public Image Image { get; set; }

}

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

    public string Image { get; set; }

    public string ImageType { get; set; }

    public bool IsDeleted { get; set; }
}

public class Image : IEntity<int>
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    public byte[] ImageBytes { get; set; }

    public string ImageType { get; set; }

    public int? ArticleId { get; set; }

    public virtual Article Article { get; set; }
}
4

2 回答 2

1

终于解决了,忘了标Imagevirtualin Contact。之后,一切都开始开箱即用。

public virtual Image Image { get; set; }
于 2017-07-20T08:58:53.307 回答
0

我认为您需要在配置中告诉您的联系人映射器以明确使用映像虚拟机的映射。当我从记忆中这样做时,可能会有一两个错别字,但它应该类似于:

.ForMember(x => x.Image, opt => opt.MapFrom(contact => Mapper.Map<ImageViewModel, Image>(contact.ImageVm);))
于 2017-07-20T08:24:20.367 回答