带有实体框架的C#AutoMapper - 使用List而不是单个可空实例

时间:2017-07-20 08:01:45

标签: c# entity-framework automapper automapper-6

我有一个非常奇怪的错误,我无法理解。我将AutoMapper 6与AutoMapper.CollectionAutoMapper.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);

enter image description here

映射:

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; }
}

2 个答案:

答案 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);))