automapper的通用扩展方法

tob*_*ias 5 .net c# generics extension-methods automapper

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; }
}
Run Code Online (Sandbox Code Playgroud)

我的域和视图类...

用于映射扩展

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

我正在使用如下

City city = GetCity(Id);
CityModel model = f.ToModel<CityModel, City>();
Run Code Online (Sandbox Code Playgroud)

但它很长

我可以像下面这样写吗?

City city = GetCity(Id);
CityModel model = f.ToModel();
Run Code Online (Sandbox Code Playgroud)

那可能吗?

kwc*_*cto 15

而不是跳过所有这些篮球,为什么不使用:

public static TDestination ToModel<TDestination>(this object source)
{
    return Mapper.Map<TDestination>(source);
}
Run Code Online (Sandbox Code Playgroud)

  • 对于任何想知道的人,我只是做了一个快速测试,在LINQPad的循环中将对象图与几个嵌套实体映射1,000,000次.没有任何可辨别的性能差异. (2认同)

Dan*_*ite 4

否,因为无法隐式推断第一个通用参数。

我会这样做

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

那么代码仍然比原来短:

var city = GetCity(Id);
var model = city.ToModel<CityModel>();
Run Code Online (Sandbox Code Playgroud)