diff --git a/LiteDB.Tests/Issues/Issue2112_Tests.cs b/LiteDB.Tests/Issues/Issue2112_Tests.cs new file mode 100644 index 000000000..2917c6bb0 --- /dev/null +++ b/LiteDB.Tests/Issues/Issue2112_Tests.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using Xunit; +using System.Linq; + +namespace LiteDB.Tests.Issues +{ + public class Issue2112_Tests + { + private BsonMapper _mapper = new BsonMapper(); + + [Fact] + public void Serialize_covariant_collection_has_type() + { + IA a = new A { Bs = new List { new B() } }; + + var docA = _mapper.Serialize(a).AsDocument; + var docB = docA["Bs"].AsArray[0].AsDocument; + + Assert.True(docA.ContainsKey("_type")); + Assert.True(docB.ContainsKey("_type")); + } + + [Fact] + public void Deserialize_covariant_collection_succeed() + { + IA a = new A { Bs = new List { new B() } }; + var serialized = _mapper.Serialize(a); + + var deserialized = _mapper.Deserialize(serialized); + + Assert.Equal(1, deserialized.Bs.Count); + } + + interface IA + { + // at runtime this will be a List + IReadOnlyCollection Bs { get; set; } + } + + class A : IA + { + public IReadOnlyCollection Bs { get; set; } + } + + interface IB + { + + } + + class B : IB + { + + } + } +} diff --git a/LiteDB/Client/Mapper/BsonMapper.Serialize.cs b/LiteDB/Client/Mapper/BsonMapper.Serialize.cs index ed26073b6..1e013b16c 100644 --- a/LiteDB/Client/Mapper/BsonMapper.Serialize.cs +++ b/LiteDB/Client/Mapper/BsonMapper.Serialize.cs @@ -135,7 +135,7 @@ internal BsonValue Serialize(Type type, object obj, int depth) // check if is a list or array else if (obj is IEnumerable) { - return this.SerializeArray(Reflection.GetListItemType(obj.GetType()), obj as IEnumerable, depth); + return this.SerializeArray(Reflection.GetListItemType(type), obj as IEnumerable, depth); } // otherwise serialize as a plain object else