2012-03-22 45 views
5
public abstract class Entity : IEntity 
{ 
    [Key] 
    public virtual int Id { get; set; } 
} 

public class City:Entity 
{ 
    public string Code { get; set; } 
} 

public class BaseViewModel:IBaseViewModel 
{ 
    public int Id { get; set; } 
} 

public class CityModel:BaseViewModel 
{ 
    public string Code { get; set; } 
} 

自分のドメインとビューのクラス...ジェネリック拡張メソッド

とマッピング拡張のための

と私は次のように使用しています

public static TModel ToModel<TModel,TEntity>(this TEntity entity) 
    where TModel:IBaseViewModel where TEntity:IEntity 
{ 
    return Mapper.Map<TEntity, TModel>(entity); 
} 

以下

City city = GetCity(Id); 
CityModel model = f.ToModel<CityModel, City>(); 

でも長すぎます

以下のように書くことができますか?

City city = GetCity(Id); 
CityModel model = f.ToModel(); 

は可能ですか?

答えて

4

第1汎用引数を暗黙に推論することはできないため、いいえです。

私はその後、コードはまだそれがあったより短絡されている。この

public static TModel ToModel<TModel>(this IEntity entity) where TModel:IBaseViewModel 
    { 
     return (TModel)Mapper.Map(entity, entity.GetType(), typeof(TModel)); 
    } 

をするでしょう:

var city = GetCity(Id); 
var model = city.ToModel<CityModel>(); 
+0

おかげでダニエル、その良いが私のために:) – tobias

+0

@tobias - 私はキャストを忘れてしまいました。 –

0

は、メンバー・メソッドとしてIEntityに拡張メソッドを置きます。次に、1つのタイプだけを渡す必要があります。代わりにだけ使用しない理由は、これらのフープ、のすべてをジャンプの

14

public static TDestination ToModel<TDestination>(this object source) 
{ 
    return Mapper.Map<TDestination>(source); 
} 
+2

LINQPadのループで、オブジェクトグラフをいくつかのネストされたエンティティで1,000,000回マッピングするという簡単なテストを行いました。パフォーマンスの違いはまったくありませんでした。 – kwcto

+1

私はこのアプローチをしばらく使用しました。しかし、静的APIはAutoMapperでは時代遅れです。 – Andreas