【问题标题】:Automapper copy List to ListAutomapper 将列表复制到列表
【发布时间】:2012-02-12 12:59:32
【问题描述】:

我有这些课程:

public class Person {
    public int Id{ get; set ;}
    public string FirstName{ get; set ;}
    public string LastName{ get; set ;}
}

public class PersonView {
    public int Id{ get; set ;}
    public string FirstName{ get; set ;}
    public string LastName{ get; set ;}
}

我定义了这个:

Mapper.CreateMap<Person, PersonView>();
Mapper.CreateMap<PersonView, Person>()
    .ForMember(person => person.Id, opt => opt.Ignore());

这就是工作:

PersonView personView = Mapper.Map<Person, PersonView>(new Person());

我想做同样的事情,但 List&lt;Person&gt;List&lt;PersonView&gt; 但我找不到正确的语法。

谢谢

【问题讨论】:

    标签: c# automapper automapper-2


    【解决方案1】:

    一旦你创建了地图(你已经完成了,你不需要为列表重复),它很简单:

    List<PersonView> personViews = 
        Mapper.Map<List<Person>, List<PersonView>>(people);
    

    您可以在AutoMapper documentation for Lists and Arrays阅读更多内容。

    【讨论】:

    • 这里需要注意的是,源模板可以是最通用的类​​型,例如PersonView[],输出可以是任何其他受支持的类型,例如IEnumerable, ICollection, IList, etc
    【解决方案2】:

    对于 AutoMapper 6

    在启动中:

    Mapper.Initialize(cfg => {
        cfg.CreateMap<Person, PersonView>();
        ...
    });
    

    然后像这样使用它:

    List<PersonView> personViews = Mapper.Map<List<PersonView>>(people);
    

    【讨论】:

      【解决方案3】:

      你也可以这样试试:

      var personViews = personsList.Select(x=>x.ToModel<PersonView>());
      

      在哪里

       public static T ToModel<T>(this Person entity)
       {
            Type typeParameterType = typeof(T);
      
            if(typeParameterType == typeof(PersonView))
            {
                Mapper.CreateMap<Person, PersonView>();
                return Mapper.Map<T>(entity);
            }
      
            return default(T);
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-30
        • 1970-01-01
        • 2016-08-14
        • 1970-01-01
        • 2018-03-19
        • 2016-10-16
        • 1970-01-01
        • 2022-01-06
        相关资源
        最近更新 更多