[英]Generic 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; }
}
我的域並查看課程...
和
用於映射擴展
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);
}
否,因為無法隱式推斷第一個通用參數。
我會這樣做
public static TModel ToModel<TModel>(this IEntity entity) where TModel:IBaseViewModel
{
return (TModel)Mapper.Map(entity, entity.GetType(), typeof(TModel));
}
然后代碼仍然比以前更短:
var city = GetCity(Id);
var model = city.ToModel<CityModel>();
將擴展方法作為成員方法放在IEntity
。 然后,您只需傳遞一種類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.