LiteDB Insert list with BsonRef

1k views Asked by At

Hi and thanks in advance everyone!

I have a collection of the following objects:

public class ItemsModel
{
    public List<int> IdCollection { get; set; }
    public string Name { get; set; }
    public int Weight { get; set; }
}

List<ItemsModel> col = ...;

I want to optimally store this with LiteDb and be able to modify the records. Each ItemsModel has a unique Name+Weight set. In the entire col, the elements of the IdCollection are also unique.

Body example:

List<ItemsModel>:
[{
    IdCollection: [1,3,5,6,...],
    Name: "first name",
    Weight: 10
},
{
    IdCollection: [2,4,...],
    Name: "second name",
    Weight: 5
}]

I want to index by Id I want to expand into two tables for easy storage in LiteDb:

[{
    _id: 1,
    NameAndWeight: {&ref: "names"}
},
{
    _id: 2,
    NameAndWeight: {&ref: "names"}
},
{
    _id: 3,
    NameAndWeight: {&ref: "names"}
},
...
]

[{
    Name: "first name",
    Weight: 10
},
{
    Name: "second name",
    Weight: 5
}]

For this I have to make new storage classes:

public class ItemsModel
{
    [BsonId]
    public int Id { get; set; }
    [BsonRef("names")]
    public NamesModel NameAndWeight { get; set; }
}
public class NamesModel
{
    [BsonId(true)]
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public int Weight { get; set; }
}

But next step I'm having trouble... Tell me, can I somehow save data using Insert array and Include in one operation? Or should I use foreach to first write the NamesModel in "names" DB, get the generated _id, then write the ItemsModel with a link to the NamesModel already written to the database?

using (var db = new LiteDatabase(_strConnection))
{
    var itemsDb = db.GetCollection<ItemsModel>("items");
    var namesDb = db.GetCollection<NamesModel>("names");
    itemsDb.EnsureIndex(x => x.Id, true);

    foreach (var group in col)
    {
        var name = new NamesModel(group.Name, group.Weight);
        namesDb.Insert(name);

        var itemDb = group.IdCollection.Select(el => new ItemsModel(el, name));
        var h = itemsDb.Insert(itemDb);
    }
}

it is too long(

1

There are 1 answers

0
awp-sirius On

Now I did like this:

using (var db = new LiteDatabase(_strConnection))
{
    var itemsDb = db.GetCollection<ItemsModel>("items");
    var namesDb = db.GetCollection<NamesModel>("names");
    itemsDb.EnsureIndex(x => x.Id, true);
    namesDb.EnsureIndex(x => x.Name);

    var temp = col.Select(el => (el.IdCollection, new NamesModel(el.Name, el.Weight))).ToList();
    namesDb.Insert(temp.Select(el => el.Item2));

    var temp2 = temp.SelectMany(gr => gr.IdCollection.Select(el => new ItemsModel(el, gr.Item2)));
    eventsIdDB.Insert(temp2);
}

Performed basic operations in linq to reduce the number of hits in liteDb