c# - 自动映射器的通用扩展方法

标签 c# .net 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; }
}

我的域和 View 类...

用于映射扩展

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

这可能吗?

最佳答案

为什么不直接使用:

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

关于c# - 自动映射器的通用扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9822723/

相关文章:

c# - 回收值(value)类型统一有什么意义吗

c# - 如何以编程方式链接 Azure DevOps 中的分支和工作项

.net - CLR 和 CLI - 有什么区别?

java泛型返回一个数组

c# - 处理 EF 中循环引用的干净方法?

c# - 如何在 MVC4 的 UserProfile 中创建自定义附加字段

c# - PrinterPlusPlus 找不到虚拟打印机

.net - Azure SDK 2.7.1 诊断配置

java - 在java中使用 'diamond'表示法表示方法

c# - 从具有指定属性的通用类列表生成 HTML 表