0

使用 Automapper 6 映射集合时遇到问题,我找不到解决方案。在updatedArticle下面的对象中,我有映射后留下的旧值CreatedUpdated值,因为它们在视图模型中不存在。但是,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; }
}
4

2 回答 2

2

折腾了两天终于解决了。从https://github.com/AutoMapper/AutoMapper.Collection安装 AutoMapper.Collection

PM> Install-Package AutoMapper.Collection
PM> Install-Package AutoMapper.Collection.EntityFramework

我必须改变的是cfg.AddCollectionMappers();EqualityComparison。例子:

Mapper.Initialize(cfg =>
{
    cfg.AddCollectionMappers();

    cfg.SetGeneratePropertyMaps<GenerateEntityFrameworkPrimaryKeyPropertyMaps<DbContext>>();

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

    cfg.CreateMap<DescriptionViewModel, Description>(MemberList.Source)
        .EqualityComparison((src, dst) => src.Id == dst.Id);
}
Mapper.AssertConfigurationIsValid();
于 2017-07-07T11:41:02.750 回答
0

您是否尝试过没有延迟加载?我自己在使用 EF Lazy Loading 和 AutoMapper 时遇到了一些问题。首先,这是非常低效的。

请参阅相关 答案

于 2017-07-06T09:24:17.987 回答