Question

If I have two models that are very different, is it defeating the purpose to even use a mapping framework such as Auto Mapper or Value Injecter?

For example, say I have two models that are structurally identical, but every property name is different, thus rending all by-convention logic useless. Is it just as well to stick to manually mapping these two models?

I guess I'm mainly trying to understand:

1) Is there any benefit to using a mapping framework aside from the code savings I gain from its by-convention mapping?

2) Is it still easier to set up mapping for the above scenario in a mapping framework vs. manually mapping in this case? (It doesn't seem like it.)

Était-ce utile?

La solution

1) Is there any benefit to using a mapping framework aside from the code savings I gain from its by-convention mapping?

I think so. It's one of those one-off kinds of things. Sure, you can write the code to manually DTO from one object to another, maybe about as fast as you can create all of the custom mapping rules. But the very second time you need to DTO, using the mapping framework pays for itself.

2) Is it still easier to set up mapping for the above scenario in a mapping framework vs. manually mapping in this case? (It doesn't seem like it.)

I think it's about the same:

Mapper.CreateMap<EntityModel, ViewModel()
    .ForMember(d => d.Prop1, o => o.MapFrom(s => s.Property1))
    .ForMember(d => d.Prop2, o => o.MapFrom(s => s.Property2))
    .ForMember(d => d.Prop3, o => o.MapFrom(s => s.Property3))
        ...
    .ForMember(d => d.PropN, o => o.MapFrom(s => s.PropertyN))
;

With this mapping, all of your DTO code will look like this:

var model = Mapper.Map<ViewModel>(entityInstance);

...versus... If you dit it manually, it looks about the same to me:

var model = new ViewModel
{
    Prop1 = entityInstance.Property1,
    Prop2 = entityInstance.Property2,
    Prop3 = entityInstance.Property3,
        ...
    PropN = entityInstance.PropertyN,
};

Another cool thing about AutoMapper over ValueInjecter is that you only need to define 1 mapping, which will then work for mapping both single instances and collections.

var models = Mapper.Map<ViewModel[]>(entityInstances);

... versus

var models = entityInstances.Select(new ViewModel
{
    Prop1 = entityInstance.Property1,
    Prop2 = entityInstance.Property2,
    Prop3 = entityInstance.Property3,
        ...
    PropN = entityInstance.PropertyN,
});

Autres conseils

For example, say I have two models that are structurally identical, but every property name is different,

It's you that are designing the view models => you have total control over them (contrary to your domain models which might be for example auto generated from a database or something by a designer) => you can name their properties accordingly :-)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top