5
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?

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
tobias
  • 1,502
  • 3
  • 22
  • 47

3 Answers3

15

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);
}
kwcto
  • 3,494
  • 2
  • 26
  • 33
  • 2
    For anyone wondering, I just did a quick test with mapping an object graph with several nested entities 1,000,000 times in a loop in LINQPad. There was no discernible performance difference whatsoever. – kwcto Mar 11 '13 at 23:58
  • 1
    I've used this approach for a while now, and it works great. But the static API is now obsolete in AutoMapper. – Andreas Feb 22 '16 at 13:11
  • 1
    Note: the static API is not obsolete anymore – mcont Jan 11 '19 at 23:27
4

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>();
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

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

Aliostad
  • 80,612
  • 21
  • 160
  • 208