Home > Net >  c# automapper map not null object to null
c# automapper map not null object to null

Time:09-21

I would like in automapper to always set on of the values of my object to null.

 CreateMap<Activity, Activity>()
                .ForMember(x => x.Category, null );

however I am receiving a null refrence exception

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=AutoMapper
  StackTrace:
   at AutoMapper.Configuration.MappingExpression`2.ForDestinationMember[TMember](MemberInfo destinationProperty, Action`1 memberOptions)
   at Application.Core.MappingProfiles..ctor() in C:\Users\Bryan.Dellinger.Apps\Documents\code\EEMRewrite\Application\Core\MappingProfiles.cs:line 17

here is my activity class

  public class Activity
    {
        public Guid Id { get; set; }
        public string Title { get; set; }
        public DateTime Start {get; set;}
        public DateTime End { get; set; }
        public string Description {get; set;}

        public Guid CategoryId { get; set; }
        public Category Category { get; set; }

    }

CodePudding user response:

Johnathan Barclay gave the correct answer in the comments which is to use:

CreateMap<Activity, Activity>()
    .ForMember(x => x.Category, opt => opt.MapFrom<Category>(_ => null);
  • Related