对于automapper通用扩展方法 [英] Generic extension method for automapper

查看:237
本文介绍了对于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; }
}

我的域名和视图类...

my domain and view classes...

映射扩展

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

这可能吗?

推荐答案

没有因为第一泛型参数不能被隐式的推断。

No because the 1st generic argument can't be implicitly inferred.

我会做到这一点。

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

那么code仍然是短比它:

Then the code is still shorted than it was:

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

这篇关于对于automapper通用扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆