Common extension method for 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 ...

and

to display the extension

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

and I use as below

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

but its long

Can I write it as shown below?

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

perhaps?

+5
source share
3 answers

No, because the 1st general argument cannot be implied.

I would do it

    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 encoded than it was:

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

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

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

IEntity -. .

0

All Articles