mbdavid / LiteDB

LiteDB - A .NET NoSQL Document Store in a single data file
http://www.litedb.org
MIT License
8.62k stars 1.25k forks source link

[BUG] BsonRef attribute not working #2359

Open JonathanBout opened 1 year ago

JonathanBout commented 1 year ago

Version Latest (5.0.17)

Describe the bug The BsonRef attribute only sets the ID of the value, without actually filing it with data from the other collection.

Code to Reproduce FooBar.cs:

class Foo
{
    public string Name { get; set; } = "";
    [BsonId]
    public int Id { get; set; }
    [BsonRef]
    public Bar Bar { get; set; } = new();
}

class Bar
{
    public string Name { get; set; } = "";
    [BsonId]
    public int Id { get; set; }
}

Program.cs:

using LiteDB;

var db = new LiteDatabase(new ConnectionString
{
    Filename = ":memory:"
});

var barCollection = db.GetCollection<Bar>();
var fooCollection = db.GetCollection<Foo>();

var bar = new Bar
{
    Name = "The Foo.Bar Object"
};

// insert element and store it's Id
var id = barCollection.Insert(bar);

// reload the object by the specified id, this gives the correct object
bar = barCollection.FindById(id);

var foo = new Foo()
{
    Name = "The Foo Object",
    Bar = bar
};

// insert into foo collection
fooCollection.Insert(foo);

// retrieve foo again from collection
foo = fooCollection.Query().Single();

// foo.Bar.Name is empty
Console.WriteLine("Name: '{0}'", foo.Bar.Name);

db.Dispose();

Expected behavior The foo.Bar.Name contains "The Foo.Bar Object"