[英]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; }
}
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? 那可能吗?
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);
}
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>();
Put the extension method on IEntity
as a member method. 将扩展方法作为成员方法放在
IEntity
。 Then you have to pass only one type. 然后,您只需传递一种类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.