C# Automapper 将列表复制到列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8899444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:03:51  来源:igfitidea点击:

Automapper copy List to List

c#automapperautomapper-2

提问by Kris-I

I have these classes :

我有这些课程:

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 ;}
}

I defined this :

我定义了这个:

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

That's work for this :

这是为此工作的:

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

I'd like make the same but for List<Person> to List<PersonView>but I don't find the right syntax.

我想做同样的List<Person> to List<PersonView>事情,但是我没有找到正确的语法。

Thanks

谢谢

采纳答案by Justin Niessner

Once you've created the map (which you've already done, you don't need to repeat for Lists), it's as easy as:

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

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

You can read more in the AutoMapper documentation for Lists and Arrays.

您可以在列表和数组AutoMapper 文档中阅读更多内容。

回答by Antonio Correia

You can also try like this:

你也可以这样试试:

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

where

在哪里

 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);
 }

回答by Ogglas

For AutoMapper 6< it would be:

对于 AutoMapper 6<,它将是:

In StartUp:

在启动中:

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

Then use it like this:

然后像这样使用它:

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