如何使用 AutoMapper 将具有子实体的实体提取到单个视图模型?
how extract entity with child entity to single view model with 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;}
}
我的 ViewModel 是:
public class MyViewModel
{
public string Property1{get;set;}
public string Property2{get;set;}
.
.
public string Property(n+m){get;set;}
}
如何使用 AutoMapper 将子实体 "ClassB" 的 class "ClassA" 映射到 "MyViewModel"?
选项#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);
我有以下实体:
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;}
}
我的 ViewModel 是:
public class MyViewModel
{
public string Property1{get;set;}
public string Property2{get;set;}
.
.
public string Property(n+m){get;set;}
}
如何使用 AutoMapper 将子实体 "ClassB" 的 class "ClassA" 映射到 "MyViewModel"?
选项#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);