AutoMapper 7.0.1
发现了一个我无法解释的有趣问题。将视图模型映射回 DB 实体对象时,Id 属性未映射且始终为 0,除非我在CreateMap
定义中明确设置其 MapFrom。
在数据库中,该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;
}
}