Reputation: 6845
I have two of class that will be map with another. MyViewClass
and MyDomainClass
public class EntityMapProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<MyDomainClass, MyViewClass>();
}
}
So I need to an extension method to map domain object to view object.
public static class MyClassMapper
{
public static MyViewClass ToView(this MyDomainClass obj)
{
return AutoMapper.Mapper.Map<MyDomainClass, MyViewClass>(obj);
}
public static IEnumerable<MyViewClass> ToView(this IEnumerable<MyDomainClass> obj)
{
return AutoMapper.Mapper.Map<IEnumerable<MyDomainClass>, IEnumerable<MyViewClass>>(obj);
}
}
But I have so many domain and view classes. So I need to create create so many extension methods and classes.
Is there any way to do this a generic way?
Upvotes: 0
Views: 2592
Reputation: 1726
The automapper already using generics so I don't any issues using direct mapper instead of extension e.g.
var view = AutoMapper.Mapper.Map<MyDomainClass, MyViewClass>(domain);
However you could write extension for IEnumerable mapping:
public static IEnumerable<TView> MapEnumerable<TDomainModel, TView>(this IEnumerable<TDomainModel> domainEnumerable)
where TDomainModel : class
where TView : class
{
return AutoMapper.Mapper.Map<IEnumerable<TDomainModel>, IEnumerable<TView>>(domainEnumerable);
}
And use it like:
IEnumerable<MyViewClass> views = domainEnumerable.MapEnumerable<MyDomainClass, MyViewClass>();
Update: Extension for single domain model
public static TView MapDomain<TDomainModel, TView>(this TDomainModel domainModel)
where TDomainModel : class
where TView : class
{
return AutoMapper.Mapper.Map<TDomainModel, TView>(domainModel);
}
Upvotes: 1