Skip to content

[BUG] BsonRef does not work in 'has many' direction #2612

@bepursuant

Description

@bepursuant

Version
v5.0.21

Describe the bug
When following the instructions regarding DbRef, I can get an object to be included in the 'has one' direction, but not in the 'has many' direction. The List property is always null despite having references in the DB and the relationship working in one irection.

Code to Reproduce
The code below exhibits this behavior in the latest version of LiteDB. Post.Comments is always null.

using LiteDB;

namespace testcore
{
    public class Post
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime CreatedOn { get;set; } = DateTime.Now;

        [BsonRef]
        public List<Comment> Comments { get; set; }
    }

    public class Comment
    {
        public int Id { get; set; }
        public string Text { get; set; }
        public DateTime CreatedOn { get; set; } = DateTime.Now;

        [BsonRef]
        public Post Post { get; set; }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            using (var db = new LiteDatabase("Filename=MyData.db;Connection=Shared"))
            {
                var post = new Post() {
                    Name = "Post 1"
                };
                db.GetCollection<Post>().Insert(post);

                var comment = new Comment() {
                    Text = "Comment 1",
                    Post = post
                };
                db.GetCollection<Comment>().Insert(comment);

                // "has one" relationship works with include
                var commentFromDb = db.GetCollection<Comment>().Include(c => c.Post).FindById(comment.Id);
                Console.WriteLine($"Comment from DB has {commentFromDb.Post} Post with Name {commentFromDb.Post?.Name} Name");

                // "has many" relationship does not work
                var postFromDb = db.GetCollection<Post>().Include(p => p.Comments).FindById(post.Id);
                Console.WriteLine($"Post from DB has {postFromDb.Comments} Comments List with {postFromDb.Comments?.Count} Comments");
            }
        }
    }
}

Expected behavior
Post.Comments should be a list containing the 1 related comment.

Screenshots/Stacktrace
Image

Additional context
I've tried to specify collection names explicitly and using other types of Ids (ex. ObjectId) with the same behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions