While implementing AutoMapper in some existing code, I came across the need to map to a nullable property. Other business logic relied on this particular long being null instead of 0. The DTO has a property that contains a (long)Id, but the Entity contains the virtual property as well as a nullable long? of the Id. Anyway after fumbling through a few tries, I finally came upon the solution and wanted to share it here.

In the MapperProfile for the direction of DTO to Entity you have to do a null check, but the trick for me was having to explicitly cast to (long?)null.

CreateMap<ExampleDto, ExampleEntity>().ForMember(ee => ee.ExampleId, options => options.MapFrom(ed => ed.ExampleProperty != null ? ed.ExampleProperty.ExampleId : (long?)null)).NoVirtualMap();

Hope someone else finds this helpful, and finds it here.

  • @BeepStreet
    link
    11 year ago

    One way to find out ;) not sure…