MapsterMapper / MapsterMapper/Mapster
Mapster throws ArgumentNullException when mapping null collection property with LINQ method (Select), unlike AutoMapper
A pull request for this has already been merged.
- #1006 by @DocSvartz — merged
- Dominant language
- C#
- Stars
- 5.2k
- Forks
- 410
- Avg merge
- 2d 12h
- Merged PRs (30d)
- 6
Description
When migrating from AutoMapper v14 to Mapster, I encountered a difference in behavior regarding null propagation for collection properties during mapping.
In AutoMapper, if a source collection property is null, calling LINQ methods like .Select() inside a mapping expression does not throw an exception — it returns null for the destination property. However, in Mapster, the same expression throws System.ArgumentNullException: 'Value cannot be null. (Parameter 'source')'.
It seems that Mapster does not apply null propagation automatically in such cases, even though the destination property is nullable.
Reproduction Steps
apster;
using MapsterMapper;
var config = new TypeAdapterConfig();
config.ForType<Source, Destination>()
.Map(s => s.ProductNames, d => d.Products.Select(p => p.Name).ToArray());
var mapper = new Mapper(config);
var source1 = new Source();
var destination1 = mapper.Map<Source, Destination>(source1); //throws System.ArgumentNullException: 'Value cannot be null. (Parameter 'source')
class Source
{
public Product[]? Products { get; set; }
}
class Product
{
public required string Name { get; set; }
}
class Destination
{
public string[]? ProductNames { get; set; }
}
Expected Behavior
The mapping should return null for Destination.ProductNames when Source.Products is null, similar to AutoMapper's behavior. Null propagation should be applied by default, or at least be configurable.
Actual Behavior
System.ArgumentNullException: 'Value cannot be null. (Parameter 'source')' is thrown at runtime.
Environment
Mapster version: 10.0.11
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the provided TypeAdapterConfig and Mapper.Map reproduction with a null Source.Products collection, then trace how the LINQ Select expression is handled during mapping. Compare the result with the stated AutoMapper behavior; done means Destination.ProductNames remains null without an ArgumentNullException, with the behavior covered by a regression test.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 65/100