AutoMapper 7.0.1
发现了一个我无法解释的有趣问题。将视图模型映射回DB实体对象时,除非我在CreateMap
定义中明确设置其MapFrom,否则Id属性不会被映射,并且始终为0。
在数据库中,TimeDetail.Id
列是一个自动递增的列,但我看不出automapper如何知道这一点……但这是我能想到的唯一原因。另外,这是用于更新现有TimeDetail的实例。
地图表达式:
var entity = Mapper.Map<TimeDetail>(viewModel);
数据库表类对象:
public partial class TimeDetail
{
public int Id { get; set; }
....other columns
}
查看模型:
public class TimeDetailsListViewModel
{
public int Id { get; set; }
... other columns
}
地图:
CreateMap<TimeDetailsListViewModel, TimeDetail>(MemberList.Destination).IgnoreAllVirtual()
.ForMember(dest => dest.Id, c => c.MapFrom(m => m.Id)) <---- Id is 0 if I don't explicitly set the map using this
.ForMember(dest => dest.StartDateTime, c => c.MapFrom(m => TimeUtilities.ConvertToUTCDateTime(m.StartDateTime).Value))
.ForMember(dest => dest.EndDateTime, c => c.MapFrom(m => TimeUtilities.ConvertToUTCDateTime(m.EndDateTime)))
;
IgnoreAllVirtual扩展方法:
public static class AutoMapperExtensions
{
public static IMappingExpression<TSource, TDestination>IgnoreAllVirtual<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> expression)
{
var desType = typeof(TDestination);
foreach (var property in desType.GetProperties().Where(p =>
p.GetGetMethod().IsVirtual))
{
expression.ForMember(property.Name, opt => opt.Ignore());
}
return expression;
}
}