AutoMapper不会自动复制相同名称的ID列

时间:2018-10-30 19:25:11

标签: c# entity-framework-6 automapper automapper-6

AutoMapper 7.0.1

发现了一个我无法解释的有趣问题。将视图模型映射回DB实体对象时,除非我在CreateMap定义中明确设置其MapFrom,否则Id属性不会被映射,并且始终为0。

在数据库中,TimeDetail.Id列是一个自动递增的列,但我看不出automapper如何知道这一点……但这是我能想到的唯一原因。另外,这是用于更新现有TimeDetail的实例。

显示Id的调试器已填充到viewModel中: enter image description here

调试器显示从id为0的automapper映射的实体对象: enter image description here

地图表达式:

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;
    }        
}

1 个答案:

答案 0 :(得分:0)

找到了答案。这与我的IgnoreAllVirtual扩展方法中的误报有关,正如this post上@Alexei答案所发现的那样。