2016-12-12 9 views
0

다른 클래스와 매핑되는 두 개의 클래스가 있습니다. MyViewClassMyDomainClassAutomapper 프로젝트()를 IEnumerable 및 단일 객체로 변환

public class EntityMapProfile : Profile 
{ 
    protected override void Configure() 
    { 
     Mapper.CreateMap<MyDomainClass, MyViewClass>(); 
    } 
} 

은 그래서 객체를 볼 수 도메인 개체를 매핑 확장 방법이 필요합니다.

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); 
    } 
} 

하지만 도메인과 뷰 클래스가 너무 많습니다. 그래서 나는 많은 확장 메소드와 클래스를 생성해야한다.

일반적인 방법으로이를 수행 할 수있는 방법이 있습니까?

답변

1

오토 매퍼는 이미 제네릭을 사용하고 있으므로 확장 대신 직접 매퍼를 사용하는 데 문제가 없습니다.

var view = AutoMapper.Mapper.Map<MyDomainClass, MyViewClass>(domain); 

당신은 IEnumerable을 매핑에 대한 확장 쓸 수 그러나 :

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); 
     } 

를 그리고이 좋아 사용

IEnumerable<MyViewClass> views = domainEnumerable.MapEnumerable<MyDomainClass, MyViewClass>(); 

업데이트 : 단일 도메인 모델에 대한 확장

public static TView MapDomain<TDomainModel, TView>(this TDomainModel domainModel) 
      where TDomainModel : class 
      where TView : class 
     { 
      return AutoMapper.Mapper.Map<TDomainModel, TView>(domainModel); 
     } 
+0

Automapper ~을 가지고있다. enerics하지만 AutoMapper.Mapper.Map <>을 항상 사용해야합니다. 확장 메서드를 만들면 모든 곳에서 사용할 수 있습니다. 감사. – barteloma

+0

단일 도메인 모델지도 확장으로 응답을 업데이트했습니다. – vadim