我有一个非常奇怪的错误,我无法理解。我将AutoMapper 6与AutoMapper.Collection
和AutoMapper.Collection.EntityFramework
一起使用。
https://github.com/AutoMapper/AutoMapper.Collection
从下面的屏幕截图中可以看出,除了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; }
}
答案 0 :(得分:1)
最后解决了这个问题,我忘记在Image
中将virtual
标记为Contact
。完成后,一切都开始工作了。
public virtual Image Image { get; set; }
答案 1 :(得分:0)
我认为您需要告诉配置中的联系人映射器明确使用映像vm。可能有一两个拼写错误,因为我是从记忆中这样做的,但它应该类似于:
.ForMember(x => x.Image, opt => opt.MapFrom(contact => Mapper.Map<ImageViewModel, Image>(contact.ImageVm);))