litedb-org/LiteDB · error · ArgumentNullException

doc

Error message

doc

What it means

Thrown by BsonMapper.ToObject(Type, BsonDocument) when doc is null. The mapper needs a source document to read field values from; null has nothing to deserialize. The generic ToObject<T> delegates here.

Source

Thrown at LiteDB/Client/Mapper/BsonMapper.Deserialize.cs:66

        private readonly HashSet<Type> _basicTypes = new HashSet<Type>
        {
            typeof(Int16),
            typeof(UInt16),
            typeof(UInt32),
            typeof(Single),
            typeof(Char),
            typeof(Byte),
            typeof(SByte)
        };

        #endregion

        /// <summary>
        /// Deserialize a BsonDocument to entity class
        /// </summary>
        public virtual object ToObject(Type type, BsonDocument doc)
        {
            if (doc == null) throw new ArgumentNullException(nameof(doc));

            // if T is BsonDocument, just return them
            if (type == typeof(BsonDocument)) return doc;

            return this.Deserialize(type, doc);
        }

        /// <summary>
        /// Deserialize a BsonDocument to entity class
        /// </summary>
        public virtual T ToObject<T>(BsonDocument doc)
        {
            return (T)this.ToObject(typeof(T), doc);
        }

        /// <summary>
        /// Deserialize a BsonValue to .NET object typed in T
        /// </summary>

View on GitHub (pinned to f906a5f850)

Solutions

  1. Null-check the document before calling ToObject and handle the missing case explicitly.
  2. If null is a valid input, return default(T) instead of calling the mapper.
  3. Check the upstream Find/FindById call that produced the document.

Example fix

// before
var entity = mapper.ToObject<MyEntity>(doc);

// after
if (doc == null) return null;
var entity = mapper.ToObject<MyEntity>(doc);
Defensive patterns

Strategy: validation

Validate before calling

if (doc == null) return default; // or throw a domain-specific error

Type guard

static bool HasDocument(BsonDocument doc) => doc != null;

Prevention

When it happens

Trigger: Calling mapper.ToObject<MyType>(null), mapper.ToObject(typeof(Foo), null), or passing a BsonDocument fetched via a lookup that returned null (e.g. FindById with a missing key).

Common situations: Deserializing a document that does not exist (FindById returned null), mapping a nullable relationship, or processing a pipeline where an earlier step yields null.

Related errors


AI-assisted analysis of litedb-org/LiteDB@f906a5f850 (2026-08-13). Data as JSON: /api/errors/6ab70e3086fcb764. Report an issue: GitHub.