Mapster icon indicating copy to clipboard operation
Mapster copied to clipboard

NullReferenceException when mapping from multiple sources when one source is null

Open jkuek opened this issue 3 years ago • 4 comments

I have 3 source items to map to a destination. There is a possibility the third item will be null.

I create a config as follows:

            var config = TypeAdapterConfig<(a, b, c), Output>.NewConfig()
                .Map(dest => dest, src => src.Item1)
                .Map(dest => dest, src => src.Item2)
                .Map(dest => dest.Application, src => src.Item3 == null ? (Application) null : new Application()
                {
                    Id = src.Item3.Id,
                    Name = src.Item3.Name
                })

My expectation was that a null value for Item3 should be handled and a null value returned for the Application property of the output.

When I run the mapping: var result = (x, y, z)Adapt<Output>(config.Config); when z is null, then a NullReferenceException is thrown.

Is this a bug?

jkuek avatar Mar 22 '22 09:03 jkuek

At first glance, this looks like a bug. I will attempt to reproduce this with a regression test and see if I can pinpoint the problem. Is it possible for you to post a stack trace, or relevant parts of a stack trace? Can you also confirm that you are using the latest version of Mapster?

andrerav avatar Mar 23 '22 09:03 andrerav

I confirm this issue is occurring using the Mapster 7.3.0 Nuget package.

The behaviour when using a tuple with a single element matches my expectations. For instance:

source.Adapt<Dest>() returns null if source is null

(source).Adapt<Dest>() returns null if source is null

but when using multiple elements it throws an exception (even without a config specified)

(source1, source2).Adapt<Dest>() throws NullReferenceException if either source is null

I'm not sure what should happen if no config is specified, but certainly in my use-case I was expecting dest.Application to be null if src.Item3 is null

jkuek avatar Mar 24 '22 02:03 jkuek

Yes! I have same problem with version 7.3.0

`config.ForType<(Pair?, Record?, Favorite?), PairDto>()

          .Map(dest => dest, src => src.Item1)

          .Map(dest => dest, src => src.Item2, srcCond => srcCond.Item2 != null)

          .Map(dest => dest, src => src.Item3, srcCond => srcCond.Item3 != null); `

0xSa9 avatar Apr 24 '22 08:04 0xSa9