【问题标题】:how extract entity with child entity to single view model with AutoMapper?如何使用 AutoMapper 将具有子实体的实体提取到单视图模型?
【发布时间】:2015-10-19 07:47:13
【问题描述】:

我有以下实体:

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”的类“ClassA”映射到“MyViewModel”?

【问题讨论】:

    标签: asp.net-mvc automapper viewmodel


    【解决方案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);
    

    【讨论】:

    • 选项 #1 是我的答案。这正是我想要的。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多