简体   繁体   中英

c# automapper map not null object to null

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

    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM