使用Automapper映射列表 [英] Mapping Lists using Automapper

查看:178
本文介绍了使用Automapper映射列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类:

 公共类Person {/ *这里道具* /}公共类PersonViewModel {/ *这里道具* /}

则列表:

 列表<&人GT;人=新的List<&人GT;();
清单< PersonViewModel> peopleVM =映射
                                .MapList<人PersonViewModel>(人); //问题就在这里。

什么是做正确的方法是什么?


解决方案

  Mapper.CreateMap<人PersonViewModel>();
peopleVM = Mapper.Map<名单,LT;人>中列出< PersonViewModel>>(人);
Mapper.AssertConfigurationIsValid();

从<一个href=\"http://automapper.$c$cplex.com/wikipage?title=Getting%20Started&referringTitle=Documentation\">Getting入门

我如何使用AutoMapper?
首先,您需要同时获得源和目的地类型的工作。目标类型的设计,可以在它生活在层的影响,但AutoMapper工作,只要最好的,因为成员的名称相匹配到源类型的成员。如果你有所谓的名字一个源成员,这将自动映射到一个名为名字的目的地成员。 AutoMapper还支持扁平化,从而可以摆脱所有你可能一路上遇到那些讨厌的空引用异常。

一旦你有你的类型,并AutoMapper一个参考,你可以创建一个映射两种类型。

  Mapper.CreateMap&LT;令,OrderDto&GT;();

左侧的类型是源类型和右边的类型是目标类型。要执行的映射,使用地图的方法。

  OrderDto DTO = Mapper.Map&LT;令,OrderDto&GT;(订单);

I have the classes:

public class Person{ /* Props here */ }

public class PersonViewModel { /* Props here */ }

Then the list:

List<Person> people = new List<Person>();
List<PersonViewModel> peopleVM = Mapper
                                .MapList<Person, PersonViewModel>(people); //Problem here.

What is the correct way to do this?

解决方案

Mapper.CreateMap<Person, PersonViewModel>();
peopleVM = Mapper.Map<List<Person>, List<PersonViewModel>>(people);
Mapper.AssertConfigurationIsValid();

From the Getting Started

How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members. If you have a source member called "FirstName", this will automatically be mapped to a destination member with the name "FirstName". AutoMapper also supports Flattening, which can get rid of all those pesky null reference exceptions you might encounter along the way.

Once you have your types, and a reference to AutoMapper, you can create a map for the two types.

Mapper.CreateMap<Order, OrderDto>();

The type on the left is the source type, and the type on the right is the destination type. To perform a mapping, use the Map method.

OrderDto dto = Mapper.Map<Order, OrderDto>(order);

这篇关于使用Automapper映射列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆