0

I don’t know how to explain it correctly, but I have a collection of classes:

using (var db = new LiteDatabase(@"MyData.db")) {
var _collection = db.GetCollection<TestClass>("mycollection");
}


public class TestClass
{
    public TestClass() {
        Task.Run(() => {
                     SomeProperty = ...; //Request to update value from outside
                 });
    }
    public int Id { get; set; }
    public string SomeProperty { get; set; } = String.Empty;
}

As you can see, a class changes its properties after instantiation from the inside.

How, after changing a property, save it back to the database, but with a new property?


P.S. If I didn’t explain the question well enough or chose the wrong path initially - write about it

SKProCH
  • 191
  • 1
  • 9

1 Answers1

1

The best way to modify your existing data when you change your entity class is use BsonDocument abstract document model. Using BsonDocument you can change fields as string and implement rules to update your model, like this:

public LiteDatabase OpenDatabase()
{
    var db = new LiteDatabase("data.db");

    // check for database version
    if (db.UserVersion == 0)
    {
        var col = db.GetCollection("mycollection");

        foreach(var doc in col.FindAll())
        {
            doc["NewProperty"] = doc["OldProperty"];

            doc.RemoveKey("OldProperty");

            col.Update(doc);
        }

        db.UserVersion = 1;
    }

    return db;
}
mbdavid
  • 1,076
  • 7
  • 8
  • Thanks @mbdavid. But how do I make UserVersion to 1 for all the newly (self) created database? So it won't have to go through the adjustment since the above-suggested code deal with an existing database. – JeeShen Lee Apr 15 '22 at 08:11