【问题标题】:AutoMapper 4.2 not ignoring properties in profileAutoMapper 4.2 不忽略配置文件中的属性
【发布时间】:2017-12-17 21:15:47
【问题描述】:

在我的 Web API 控制器方法中,在将 UpdatePlaceDTO 映射到 PlaceMaster 之前,我进行了数据库调用以填充 Map 未覆盖但由于某种原因 AutoMapper 使这些属性为空的属性。

var mappedPlaceMaster = _mapper.Map<PlaceMaster>(placeMasterDTO);
// mappedPlaceMaster.EntityId is null 

我尝试了很多 IgnoreExistingMembers 的解决方案,但没有一个有效。

这就是我所拥有的

    public class PlaceMapperProfile : Profile
    {

        protected override void Configure()
        {
            // TO DO: This Mapping doesnt work. Need to ignore other properties
            //CreateMap<UpdatePlaceDto, PlaceMaster>()
            //    .ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
            //    .ForMember(d => d.Description, o => o.MapFrom(s => s.Description))
            //    .ForMember(d => d.ParentPlaceId, o => o.MapFrom(s => s.ParentPlaceId))
            //    .ForMember(d => d.LeftBower, o => o.MapFrom(s => s.LeftBower))
            //    .ForMember(d => d.RightBower, o => o.MapFrom(s => s.RightBower)).IgnoreAllNonExisting();
         }
     }

这是扩展

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
        {
            foreach (var property in expression.TypeMap.GetUnmappedPropertyNames())
            {
                expression.ForMember(property, opt => opt.Ignore());
            }
            return expression;
        }

我使用模块将映射器注入我的依赖项

protected override void Load(ContainerBuilder builder)
        {
            //register all profile classes in the calling assembly
            var profiles =
                from t in typeof(Navigator.ItemManagement.Data.MappingProfiles.PlaceMapperProfile).Assembly.GetTypes()
                where typeof(Profile).IsAssignableFrom(t)
                select (Profile)Activator.CreateInstance(t);

            builder.Register(context => new MapperConfiguration(cfg =>
            {
                foreach (var profile in profiles)
                {
                    cfg.AddProfile(profile);
                }


            })).AsSelf().SingleInstance();

            builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve))
                .As<IMapper>()
                .SingleInstance();
        }

我在某个线程中看到 _mapper.Map 实际上创建了一个新对象,那么我们如何使它成为对现有属性值的“附加”?

【问题讨论】:

    标签: c# automapper automapper-4


    【解决方案1】:

    好的,我找到了解决方案。它就在我面前,但我没看到!

    我只需要使用 Map 函数的重载,它不会创建 PlaceMaster 的新实例,而是分配地图中可用的属性。

    mappedPlaceMaster = _mapper.Map(placeMasterDTO, placeMasterFromDatabase);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      相关资源
      最近更新 更多