1

How to use DbRef in LiteDB. I have classes for both Customer and Job. I want the Customer to store a list of jobs that the Customer has.

So in the Customer class, I need to have aDbRef<Job> Jobs from what I understand. I have several issues. First, DbRef is not recognized as a type with using LiteDB. Second, I have no idea how to implement it

Job.cs

namespace HMDCompare.Classes
{
  public class Job
  {
    public int id { get; set; }
    public string name { get; set; }
  }
}

Customer.cs

using LiteDB;

namespace HMDCompare.Classes
{
    public class Customer
    {
        [BsonId]
        public int Id { get; set; }

        public string Name { get; set; }
        public string[] Phones { get; set; }
        public bool IsActive { get; set; }

        public DbRef<Job> Jobs { get; set; }
    }
}

for the DbRef I get in Visual Studio: The type or Namespace name 'DbRef' could not be found.

I am developing in C#/ASP.net 4.5 and with LiteDB 2.0.0-rc

Liron Harel
  • 10,819
  • 26
  • 118
  • 217
  • 1
    A lot of things changed on the V2 version, and it seems DBRef is no more a type but a function, take a look at this example: https://github.com/mbdavid/LiteDB/blob/7aba1cd5417d3332eccfe365d061701195744fa2/LiteDB.Tests/Mapping/IncludeTest.cs – Gusman Mar 09 '16 at 17:35
  • @Gusman good find. I will go over it and see how it works. Thanks – Liron Harel Mar 09 '16 at 17:37

2 Answers2

0

I'm very late, I know. But for anyone who stumbles across this: you should use the BsonRef Attribute. The model class would then look like this:

using LiteDB;

namespace HMDCompare.Classes
{
    public class Customer
    {
        [BsonId]
        public int Id { get; set; }

        public string Name { get; set; }
        public string[] Phones { get; set; }
        public bool IsActive { get; set; }
        [BsonRef("collectionName")]
        public Job[] Jobs { get; set; }
    }
}

Instead of collectionName you can use the name of the collection where the data is stored, or you can leave it out.

Jonathan
  • 330
  • 1
  • 10
-1

Using LiteDB.2.0.0-rc and following the example in test page, worked fine for me.

public IncludeDatabase() : base("mydb.db")
{
}

public LiteCollection<Folder> Folders { get { return this.GetCollection<Folder>("Folders"); } }
public LiteCollection<SubFolders> SubFolders { get { return this.GetCollection<Media>("SubFolders"); } }

protected override void OnModelCreating(BsonMapper mapper)
{
    mapper.Entity<SubFolder>()
        .DbRef(x => x.Folder, "Folders");
}

.....

add

var subFolder = new SubFolder()
{
    Name = file.Name,
    Folder = new Folder { Id = idFolder },
};

using (var db = new IncludeDatabase())
{                
    db.SubFolders.Insert(subFolder);
}

get

using (var db = new IncludeDatabase())
{                
    return db.SubFolders
        .Include(x => x.Folder)
        .FindAll().ToList();
}
Thalles Noce
  • 791
  • 1
  • 9
  • 20