0

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?

barteloma
  • 6,403
  • 14
  • 79
  • 173

1 Answers1

1

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);
        }
vadim
  • 1,698
  • 1
  • 10
  • 19
  • Automapper has generics but I need use AutoMapper.Mapper.Map<> all time. If I create extension method, I can use it everywhere. Thanks. – barteloma Dec 12 '16 at 12:14
  • I updated answer with single domain model map extension too – vadim Dec 12 '16 at 14:16