So if you’ve bothered reading my posts in the past, and don’t worry cause I haven’t, you might have seen me express my rule about not wanting to use third party stuff. Well things change. Actually they don’t, as I’m not bending the rule because I’m becoming a better person, just more lazy. This is where Automapper comes in.
Automapper is pretty much what it sounds like, it maps class properties automatically. Maybe a more clevererest name would have been ClassPropertyAutoMapper, but the guys who made it shouldn’t be persecuted for lacking creativity.
How simple is Automapper? Simple enough that even you can use it. Now that’s simple! Say you have two classes, a entity class and a model, and you want to map the model to the entity in the constructor. You could do:
public class SomeModel
{
public SomeModel(SomeEntity someEntity)
{
SomeProperty = someEntity.SomeProperty;
}
}
But where’s the lazyiness? I expect so much less from you. But it’s ok, salvation is right here:
public SomeModel(SomeEntity someEntity)
{
Mapper.CreateMap();
Mapper.Map(someEntity, this);
}
But… but what if there are properties on SomeModel that don’t directly map by name? Well, there’s an ap…i for that. (Not sure that even makes sense but it was clever.)
public SomeModel(SomeEntity someEntity)
{
Mapper.CreateMap<FiftyPostUser, UserInfoViewModel>()
.ForMember(test => test.Status, tester => tester.MapFrom(item => item.Status.ToString()));
Mapper.Map(someEntity, this);
}
So I know you’re thinking that there’s a catch, well there is. You have to actually get the dll and reference in your project. I know! Work is hard. Why can’t these guys just come to your place of work/home/mom’s basement and do it for you? What kind of world is it when you can’t get all that for free? Personally, I hate it.