this post was submitted on 16 Jul 2023
14 points (100.0% liked)

.NET

1466 readers
5 users here now

Getting started

Useful resources

IDEs and code editors

Tools

Rules

Related communities

Wikipedia pages

founded 1 year ago
MODERATORS
 

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.

you are viewing a single comment's thread
view the rest of the comments
[–] BeepStreet 2 points 1 year ago (5 children)

Wouldn't this work just as well? ed => ed.ExampleProperty?.ExampleId

[–] [email protected] 1 points 1 year ago (2 children)

I can certainly test this. My question would then be, will this result in actually mapping a null in the dto, or would the .ExampleProperty? just "be null" and cause the long property to instantiate to 0?

[–] BeepStreet 1 points 1 year ago

One way to find out ;) not sure...

[–] [email protected] 1 points 1 year ago (1 children)

i'm pretty sure it'll be a long? - did you try it?

[–] [email protected] 1 points 1 year ago* (last edited 1 year ago) (1 children)

So.. When I change...

.ForMember(ee => ee.ExampleId, options => options.MapFrom(ed => ed.ExampleProperty != null ? ed.ExampleProperty.ExampleId : (long?)null))

TO:

.ForMember(ee => ee.ExampleId, options => options.MapFrom(ed => ed.ExampleProperty?.ExampleId))

I am presented with: CS8072 - An expression tree lambda may not contain a null propagating operator.

[–] [email protected] 2 points 1 year ago

there you go! thanks for updating, good to know

load more comments (2 replies)