Details
-
Bug
-
Resolution: Fixed
-
Unknown
-
None
-
None
-
Minor Change
Description
Summary
When a custom collection property is serialized, an exception is thrown because MongoDB.Bson default serialization provider implicitly assumes any IEnumerable<T> can be serialized as type List<T>.
Version: v2.16.0
How to Reproduce
using MongoDB.Bson;
|
using System.Collections;
|
using System.Collections.Generic;
|
|
|
namespace MongoDbBsonTest
|
{
|
public static class Program |
{
|
public static void Main() |
{
|
var obj = new Node() |
{
|
Children = new FooCollection() |
{
|
new Node() { Prop = "Test" } |
}
|
};
|
var bson = obj.ToBson<object>();
|
}
|
}
|
|
|
public class Node |
{
|
public string Prop { get; set; } |
public INodeCollection Children { get; set; } |
}
|
|
|
public interface INodeCollection : ICollection<Node> |
{
|
}
|
|
|
public class FooCollection : INodeCollection |
{
|
private readonly List<Node> data = new(); |
public int Count => data.Count; |
public bool IsReadOnly => false; |
public void Add(Node item) => data.Add(item); |
public void Clear() => data.Clear(); |
public bool Contains(Node item) => data.Contains(item); |
public void CopyTo(Node[] array, int arrayIndex) => data.CopyTo(array, arrayIndex); |
public IEnumerator<Node> GetEnumerator() => data.GetEnumerator(); |
public bool Remove(Node item) => data.Remove(item); |
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
}
|
}
|