使用 Automapper 6 映射集合时遇到问题,我找不到解决方案。在updatedArticle
下面的对象中,我有映射后留下的旧值Created
和Updated
值,因为它们在视图模型中不存在。但是,Descriptions 中的Created
和中的值会丢失。Updated
通过视图模型传入的值都已正确更新。我究竟做错了什么?Automapper 也丢失了 Article 的 Entity Framework 6 映射,因为这些值也丢失了。
控制器方法:
public async Task<IHttpActionResult> UpdateArticle(ArticleViewModel articleVm)
{
Article articleOriginal = await iArticleRepository.GetAsync(articleVm.Id);
Article updatedArticle = Mapper.Map<ArticleViewModel, Article>(articleVm, articleOriginal);
return Ok();
}
映射:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ArticleViewModel, Article>()
.ForMember(x => x.Created, opt => opt.Ignore())
.ForMember(x => x.Updated, opt => opt.Ignore());
cfg.CreateMap<DescriptionViewModel, Description>()
.ForMember(x => x.Created, opt => opt.Ignore())
.ForMember(x => x.Updated, opt => opt.Ignore())
.ForMember(x => x.ArticleId, opt => opt.Ignore())
.ForMember(x => x.Article, opt => opt.Ignore());
}
Mapper.AssertConfigurationIsValid();
视图模型:
public class ArticleViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<DescriptionViewModel> Descriptions { get; set; }
}
public class DescriptionViewModel
{
public int Id { get; set; }
public string Heading { get; set; }
}
楷模:
public class Article : IEntity<int>
{
public Article()
{
Descriptions = new List<Description>();
}
[Key]
public int Id { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
[MaxLength(256)]
public string Name { get; set; }
public virtual ICollection<Description> Descriptions { get; set; }
}
public class Description: IEntity<int>
{
[Key]
public int Id { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
[MaxLength(256)]
public string Heading { get; set; }
public int ArticleId { get; set; }
public virtual Article Article { get; set; }
}