litedb-org/LiteDB · error · ArgumentNullException
entity
Error message
entity
What it means
Thrown by BsonMapper.ToDocument(Type, object) when entity is null. The serializer must read member values from a real instance; null has no members to read. The generic ToDocument<T> delegates here.
Source
Thrown at LiteDB/Client/Mapper/BsonMapper.Serialize.cs:15
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
namespace LiteDB
{
public partial class BsonMapper
{
/// <summary>
/// Serialize a entity class to BsonDocument
/// </summary>
public virtual BsonDocument ToDocument(Type type, object entity)
{
if (entity == null) throw new ArgumentNullException(nameof(entity));
// if object is BsonDocument, just return them
if (entity is BsonDocument) return (BsonDocument)(object)entity;
return this.Serialize(type, entity, 0).AsDocument;
}
/// <summary>
/// Serialize a entity class to BsonDocument
/// </summary>
public virtual BsonDocument ToDocument<T>(T entity)
{
return this.ToDocument(typeof(T), entity)?.AsDocument;
}
/// <summary>
/// Serialize to BsonValue any .NET object based on T type (using mapping rules)
/// </summary>View on GitHub (pinned to f906a5f850)
Solutions
- Null-check the entity before calling ToDocument.
- If null is meaningful, decide whether to skip serialization or store BsonValue.Null explicitly.
- Validate the source that produced the entity (repository lookup, deserialization).
Example fix
// before var doc = mapper.ToDocument(entity); // after if (entity == null) throw new ArgumentNullException(nameof(entity)); var doc = mapper.ToDocument(entity);
Defensive patterns
Strategy: validation
Validate before calling
if (entity == null) throw new ArgumentNullException(nameof(entity));
Prevention
- Null-check entities from factories/lookups before serializing.
- Filter null elements out of collections before bulk ToDocument.
When it happens
Trigger: Calling mapper.ToDocument(typeof(Foo), null), mapper.ToDocument<MyType>(null), or passing an entity variable that was never assigned (e.g. a not-found lookup result).
Common situations: Inserting/upserting an object that came back null from a factory, serializing a nullable reference that was not null-checked, or processing a list that contains a null element.
Related errors
AI-assisted analysis of litedb-org/LiteDB@f906a5f850 (2026-08-13).
Data as JSON: /api/errors/fc7360c7653f7436.
Report an issue: GitHub.