There are various object mappers available like AutoMapper, TinyMapper, EmitMapper, ValueInjector and many more mappers. They all provide a flexible way to do the mappings from one object to another without much effort.
When it comes to performance nothing can beat good old manual mappings. The downside is, it get mixed up under projection from LINQ queries. By mixing projection, we hard code the mapping between model, if again it needs to be mapped to some other place, then write that again. The ideal approach should be separating the mapping to some other place, it also takes care of SRP pattern and also our code manageability increase by keeping projection/mapping separately.
The usage can be very simple. Here is expression technique to map one entity model to view model.
Expression is available from System.Linq.Expressions namespace.
It is just a lambda expression which could be used at any place. The consumption could be really easy to use.
The examples based on Select and FirstOrDefault:
In next version, I would target it through Attributes and T4 for automatic mapping generation.
When it comes to performance nothing can beat good old manual mappings. The downside is, it get mixed up under projection from LINQ queries. By mixing projection, we hard code the mapping between model, if again it needs to be mapped to some other place, then write that again. The ideal approach should be separating the mapping to some other place, it also takes care of SRP pattern and also our code manageability increase by keeping projection/mapping separately.
The usage can be very simple. Here is expression technique to map one entity model to view model.
public Expression<Func<SecurityUser, UserBasicInfo>> MapUserBasicInfo()
{
return (user) => new UserBasicInfo
{
FullName = user.Person.FirstName + " " + user.Person.MiddleName + " " + user.Person.LastName,
UserName = user.UserName,
UserId = user.Id
};
}
Expression is available from System.Linq.Expressions namespace.
It is just a lambda expression which could be used at any place. The consumption could be really easy to use.
The examples based on Select and FirstOrDefault:
model.Select(MapUserBasicInfo())
.Select(MapUserBasicInfo()).FirstOrDefault()
In next version, I would target it through Attributes and T4 for automatic mapping generation.
Comments
Post a Comment