Thursday, April 5, 2012

How to effectively use Automapper with DbContext/Entity Framework

Generally the AutoMapper is used to map the field values in between  Business and DTO objects/viceversa in irrespective of types. To speed up my development used the AutoMapper for map the Entity to POCO object. In Later stage i feel the automapper is neglecting the lazy loading of Entity Framework, since by default AutoMapper will map the Fields based on the naming convention. Ex: Having the EF structure like below



Retrieved the Customer object from context and mapped it to POCO trainer object to use in UI/BO layer.

 customer = AutoMapper.
Mapper.Map<Common.Customer, Data.Model.Customer>(dbCustomer);

 The AutoMapper implicitly map the customer along with its down level child objects. ie: it map the user, customernutrition, etc. To avoid this I have added a extension method and ignore the properties which are belongs Common namspace.

public static IMappingExpression<TSource, TDestination> IgnoreSynsObjects<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{var flags = BindingFlags.Public | BindingFlags.Instance;
var sourceType = typeof(TSource);
var destinationProperties = typeof(TDestination).GetProperties(flags);
foreach (var property in destinationProperties)
{if (property.PropertyType.FullName.Contains("SYNS.Common.")
||property.PropertyType.FullName.Contains("SYNS.Common.TrackableCollection"))
{
expression.ForMember(property.Name, opt => opt.Ignore());
}
}return expression;
}

And the mapping should be as

AutoMapper.Mapper.CreateMap<Data.Model.Customer, Common.Customer>().IgnoreAllNonExisting();


The instance mapping should be as like follow


customer = AutoMapper.Mapper.Map(customer, dbCustomer);

After this change, the lazyloading is not neglected by the Automapper.

No comments:

Post a Comment