通用的Automapper扩展方法

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

这是可能的吗?
3个回答

15

为什么不直接使用以下方法,而不必跳过所有这些步骤:

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

2
对于任何想知道的人,我刚刚在LINQPad中进行了一个快速测试,将一个包含多个嵌套实体的对象图映射1,000,000次循环。完全没有可辨别的性能差异。 - kwcto
1
我已经使用这种方法有一段时间了,它非常有效。但是在AutoMapper中,静态API现在已经过时了。 - Andreas
1
注意:静态 API 不再过时。 - mcont

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
将扩展方法放在“IEntity”上作为成员方法。然后您只需要传递一个类型即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接