关于AutoMapper处理null集合默认行为的合理性探讨
Hey everyone,
I wanted to open up a discussion about a behavior in AutoMapper that caught me off guard recently, and get your thoughts on whether it makes sense to adjust how it works by default.
The Current Behavior
Right now, when AutoMapper maps a collection property, if the source value is null, it automatically sets the target property to an empty collection (like List<T>() or HashSet<T>()), instead of leaving it as null. This is intentional—AutoMapper aligns this with Entity Framework practices and the Framework Design Guidelines, which state that C# references, arrays, lists, collections, dictionaries, and IEnumerables should never be null.
Why This Feels Problematic to Me
Here's the thing: null and empty collections aren't interchangeable—they carry very different meanings in most codebases:
- A
nullcollection often signals that the data wasn't loaded, isn't applicable to the context, or is missing entirely (like a related entity that wasn't fetched via eager loading). - An empty collection explicitly tells you there are no items present for that property.
Forcing the "never null" guideline as the default assumes every developer and codebase follows this rule, which just isn't true. I've worked on projects where null checks are critical for handling uninitialized or missing data, and AutoMapper's current behavior requires extra workarounds to preserve the original null state—workarounds that are easy to miss and can lead to subtle bugs.
A Proposed Fix
Instead of making this behavior mandatory, I think AutoMapper should turn this into an optional configuration setting. Developers who want to stick to the Framework Design Guidelines can enable the "convert null to empty collection" behavior, while those who need to preserve null values for collections can disable it with a simple flag or setting.
What Do You Think?
I'm curious to hear from others in the community:
- Have you run into issues because of AutoMapper's current default handling of null collections?
- Do you prefer auto-converting nulls to empty collections, or preserving null values—and why does that make sense for your use case?
- Would an optional configuration flag be a practical, user-friendly solution here?
内容的提问来源于stack exchange,提问作者Shakirov Ruslan

