Generic extension method for automapper

强颜欢笑 提交于 2019-12-01 03:10:24

问题


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...

and

for mapping extension

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

and i am using like below

City city = GetCity(Id);
CityModel model = f.ToModel<CityModel, City>();

but its long

can i write it like below?

City city = GetCity(Id);
CityModel model = f.ToModel();

is that possible?


回答1:


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

I would do this

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

Then the code is still shorted than it was:

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



回答2:


Instead of jumping through all of those hoops, why not just use:

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



回答3:


Put the extension method on IEntity as a member method. Then you have to pass only one type.



来源:https://stackoverflow.com/questions/9822723/generic-extension-method-for-automapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!