2015-10-19 52 views
0

我有以下实体:如何使用AutoMapper将实体与子实体提取为单视图模型?

public class ClassA 
{ 
    public int Id{get;set;} 
    public string Property1{get;set;} 
    public string Property2{get;set;}   
    . 
    . 
    public string Property(n){get;set;} 
    public ClassB Item{get;set;} 
} 

public class ClassB 
{ 
    public int Id{get;set;} 
    public string Property(n+1){get;set;} 
    public string Property(n+2){get;set;} 
    . 
    . 
    public string Property(n+m){get;set;} 
} 

我的视图模型为:

public class MyViewModel 
{ 
    public string Property1{get;set;} 
    public string Property2{get;set;} 
    . 
    . 
    public string Property(n+m){get;set;} 
} 

我怎么能映射类 “ClassA的” 与孩子实体 “ClassB的” 到 “MyViewModel” 与AutoMapper?

回答

1

选项#1:

Mapper.CreateMap<ClassA, MyViewModel>(); 
Mapper.CreateMap<ClassB, MyViewModel>() 
    .ForMember(dest => dest.Id, opt => opt.Ignore()); 

var vm = Mapper.Map<MyViewModel>(classA); 
Mapper.Map<ClassB, MyViewModel>(classA.Item, vm); 

选项#2:

Mapper.CreateMap<ClassA, MyViewModel>() 
    .ForMember(dest => dest.Property(n+1), opt => opt.MapFrom(source => Item.Property(n+1))) 
    .ForMember(...); //for each of ClassB property 

var vm = Mapper.Map<MyViewModel>(classA); 
+0

选项1是我answer.This正是我一直在寻找for.thanks很多 –

相关问题