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.

Monday, March 26, 2012

Way to resolve Unit Test Adapter threw exception in Visual Studio

I tried to execute the unit test with code coverage option, unfortunately it throws following exception


Unit Test Adapter threw exception:
Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information..

On analysis found that the Code Coverage Settings file is pointing the wrong re-singing key file. I have point this to the correct path, after this change able to run the unit test with code coverage. The Steps are


Edit the test settings



In "Data and Diagnostics" option, double click "Code Coverage".

Point the correct snk file, then you can able to run the unit test with code coverage.