Autmapper嵌套映射

问题描述 投票:0回答:1

我有以下主要课程:

public class ResearchOutcome 
{
    public ResearchOutcomeCategory ResearchOutcomeCategory { get; set; }
    public string? UniqueIdentifier { get; set; }
}

类别类别为:

public class ResearchOutcomeCategory 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string? Description { get; set; }
}

以上类的View模型是:

public class ResearchOutcomeDetailVm : IMapFrom<ResearchOutcome>
{
    public int Id { get; set; }
    public virtual ResearchOutcomeCategoryDetailVm ResearchOutcomeCategory { get; set; }
}

public class ResearchOutcomeCategoryDetailVm : IMapFrom<ResearchOutcomeCategory>
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

现在,我使用了以下映射配置文件:

   // First this one
        profile.CreateMap<ResearchOutcomeCategory, ResearchOutcomeCategoryDetailVm>();
        profile.CreateMap<ResearchOutcome, ResearchOutcomeDetailVm>();


   //Then I tried this one


        profile.CreateMap<ResearchOutcome, ResearchOutcomeDetailVm>()
            .ForMember(o => o.ResearchOutcomeCategory, 
                cat => cat.MapFrom( o => o.ResearchOutcomeCategory));

但是ResearchOutcomeCategory始终为null。任何帮助,将不胜感激。

nested mapping automapper
1个回答
0
投票

经过更多挖掘之后,我发现我没有“包含”查询中的相关项,因此,视图模型始终为空。我很傻:D

关于映射,如果属性(甚至是复杂的属性)具有相同的名称,则映射器将自动映射它们。所以这行很简单

            profile.CreateMap<ResearchOutcomeCategory, ResearchOutcomeCategoryDetailVm>();

希望对别人有帮助

© www.soinside.com 2019 - 2024. All rights reserved.