AutoMapper 无法在对象内部映射对象

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

我正在尝试将 ViewModel 映射到 Model。我的模型看起来像这样:

public class FinalsViewModel                   
{                                                  
    public FinalViewMode First { get; set; }                                          
    public FinalViewModel Second { get; set; }                                             
} 

public class Finals
{
    public Final First { get; set; }                                            
    public Final Second { get; set;  }
} 

// And Final:

public class FinalViewModel
{    
    public int Another { get; set; }
}  

public class Final
{    
    public int Order { get; set; }
    public int Another { get; set; }
}                                                     

我创建了如下所示的映射:

CreateMap<FinalsViewModel, Finals>()
                .ForMember(src => src, opt => opt.MapFrom((src, dest) =>
                {
                    var list = new List<Final>();
                    if (src.First != null && src.First?.Another != null)
                        list.Add(new Final { Order = 1, Another = src.First.Another });
            
                    if (src.Second != null && src.Second?.Another != null)
                        list.Add(new Final { Order = 2, Another = src.Second.Another });
                   
            
                    var result = new Finals() // logic for mapping First = First, Second = Second etc;
            
                    return result;
                }));

我从这个映射中得到错误:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> AutoMapper.AutoMapperConfigurationException: Custom configuration for members is only supported for top-level individual members on a type.

我的问题是,如何重写此配置以将对象映射到另一个对象内?

c# automapper
1个回答
0
投票

问题是你的

ForMember(source=>source)
; AutoMapper默认映射源中的每个属性,第一个参数是
Expression
,它设计用于获取成员名称,
x=>x.First 
将获取
First
及其类型。

您想要将

FinalsViewModel
映射到
Finals
。首先你需要创建一张
FinalsViewModel
=>
Finals
的地图 那么你需要创建一个
FinalViewMode
=>
Final

的地图
CreateMap<FinalsViewModel, Finals>();
CreateMap<FinalViewMode,Final>();

// you can also use `.ForMember()` to do more.
© www.soinside.com 2019 - 2024. All rights reserved.