2012-03-22 88 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

不,因为第一个泛型参数不能被隐式推断。

我会做这个

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 2012-03-22 13:02:49

+0

@tobias - 我忘了演员。 – 2012-03-22 13:03:26

0

把扩展方法上IEntity为成员的方法。那么你只能通过一种类型。

14

而不是通过所有的篮球,为什么不使用的跳跃:

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

对于任何想知道的人,我只是做了一个快速测试,在LINQPad的一个循环中映射一个具有1,000,000次多个嵌套实体的对象图。没有任何明显的性能差异。 – kwcto 2013-03-11 23:58:32

+1

我已经使用这种方法一段时间了,它的效果很好。但是静态API现在在AutoMapper中已经过时了。 – Andreas 2016-02-22 13:11:27