Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Missing _type when serializing a covariant collection #2112

Closed
guillaume86 opened this issue Dec 5, 2021 · 0 comments
Closed

Missing _type when serializing a covariant collection #2112

guillaume86 opened this issue Dec 5, 2021 · 0 comments

Comments

@guillaume86
Copy link
Contributor

guillaume86 commented Dec 5, 2021

When serializing a covariant generic type (like ReadOnlyCollection<out T>), it is possible to serialize objects with the _type missing (which will cause deserialization to fail).

Here's a minimum repro:

using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace LiteDB.Tests;

public class LiteDB_Bug
{
    [Fact]
    public void CovariantCollectionIsMissingTypeInfo()
    {
        IA a = new A { Bs = new List<B> { new B() } };

        var docA = BsonMapper.Global.Serialize<IA>(a).AsDocument;
        var docB = docA["Bs"].AsArray[0].AsDocument;

        Assert.True(docA.ContainsKey("_type")); // OK
        Assert.True(docB.ContainsKey("_type")); // KO
    }

    interface IA
    {
        // at runtime this will be a List<B>
        IReadOnlyCollection<IB> Bs { get; set; }
    }

    class A : IA
    {
        public IReadOnlyCollection<IB> Bs { get; set; }
    }

    interface IB { }
    class B : IB { }
}

The issue seems to come from this line which uses obj.GetType() and pass down that type, when it should use type to extract the item type.

guillaume86 added a commit to guillaume86/LiteDB that referenced this issue Dec 5, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant