Help Me Understand AutoMapper

2019-07-25 15:11发布

问题:

What is the point of AutoMapper? Could someone give me a really simple example?

I have watched the video on it, but it is just not clicking.

Sam

回答1:

Typically AutoMapper is great at mapping between data entities and business models. E.g., lets say for instance, I have a data domain type, call it PersonEntity, and it has an array of properties: FirstName, Surname, Gender etc. I don't want to expose my data domain type through to the consuming application, so I can define business domain types, e.g. Person, now the Person type can contain additional business logic, such as GetRelatedPersons, etc, which may not be functionality tied to your data domain. In this case, I have two types, PersonEntity and Person which at some point I will have to write boilerplate code to copy the properties from one to the other. I could do this a variety of ways, I could:

1.Copy Constructor:

public Person(PersonEntity entity) {

2.Generalised Mapping Method:

public Person CreatePerson(PersonEntity entity) {

3.Implicit/Explicit Conversion:

public static implicit operator Person(PersonEntity entity) {

But what AutoMapper allows you to do, is easily create a mapping process between those two types. So in its simiplist form, I could:

Person person = Mapper.Map<PersonEntity, Person>(entity);

By using a convention-first approach, the AutoMapper framework will translate matching properties from one instance to the next. It also allows you to customise how the types are mapped if you want more fine grained control.

Hope that helps.



回答2:

In ASP.NET MVC (since you've tagged that), AutoMapper makes the painful task of mapping your ViewModels to your domain models (e.g Entity Framework POCO's, Linq-To-Sql classes) much easier.

Most of the time, our ViewModels contain many entities, so we can't simply do context.AddObject(viewModel). Usually we have to break apart the ViewModel, do multiple adds, etc.

This manual stitching makes your Controller "fat", which is the opposite of what it should be.

Enter AutoMapper.

There is a good/simple example here of the above here.



回答3:

say you have two classes

class A
{
  public string MyName;
  public string MyAge;
}

class B
{
  public string MyViewsName;
  public string MyViewsAge;
}

I would say, (A is Source, B is destination.)

Map<A,B>().ForMember(dest => dest.MyViewsName, o => o.MapFrom(src => src.MyName))
          .ForMember(dest => dest.MyViewsAge, o => o.MapFrom(src => src.MyAge));

so now I can have an object A with some filled in properties, and say

var myBobject = MyMap.Map(MyAObject, new B());

now the properties got mapped to the object for you :D

its a fancy copy constructor if you are familar with C++ :D, Hope that helps