2016-12-12 3 views
0

私は別のクラスにマップするクラスを2つ持っています。 MyViewClassMyDomainClassAutomapper Project()を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

オートマトンはすでにジェネリックを使用していますので、拡張子の代わりにダイレクトマッパーを使用しても問題はありません。

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をマッピングするための拡張を書くことができしかし

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

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 〜を持つ私はAutoMapper.Mapper.Mapを使用する必要があります。私が拡張メソッドを作成すると、どこでも使えます。ありがとう。 – barteloma

+0

私は単一ドメインモデルマップ拡張でも答えを更新しました – vadim

関連する問題