LiteDb persisting instance vs open/close

152 views Asked by At

I love LiteDb, but its Achilles heel is the lack of support or community (a forum or Discord would be good, but sadly, no dice).

This will be obvious to some, but I'm exploring keeping an instance of the database open for the lifetime of the application vs open and closing it on each CRUD, storing the data objects in memory in between.

I have the POCO:

internal class Game
{
    public ObjectId Id { get; set; }

    public string Name { get; set; }
}

When I do this:

using (var db = new LiteDatabase(ConnectionString))
{
    var games = db.GetCollection<Poco.Game>("games");
    Poco.Game newGame = new Poco.Game() { Id = ObjectId.NewObjectId(), Name = "R-Type" };
    games.Insert(newGame);

    // doing other processing in the app here

    ILiteCollection<Game> recalledGames;
    recalledGames = (ILiteCollection<Game>)db.GetCollection<Game>("games");

    Game firstGame = recalledGames.FindAll().First();
    firstGame.Name = "BC's quest for tires";

    recalledGames.Update(firstGame);
}

It works as expected. That is the first game's Name is first added as "R-Type" and then updated to "BC's Quest for Tires" if I explore the database via LiteDB Studio while step debugging. However, if I do this:

using (var db = new LiteDatabase(ConnectionString))
{
    var games = db.GetCollection<Poco.Game>("games");
    Poco.Game newGame = new Poco.Game() { Id = ObjectId.NewObjectId(), Name = "R-Type" };
    games.Insert(newGame);

    // doing other processing in the app here
}

ILiteCollection<Game> recalledGames;
using (var db = new LiteDatabase(ConnectionString))
{
    recalledGames = (ILiteCollection<Game>)db.GetCollection<Game>("games");
}

Game firstGame = recalledGames.FindAll().First();

firstGame.Name = "BC's quest for tyres";

using (var db = new LiteDatabase(ConnectionString))
{
    var Games = db.GetCollection<Game>();
    Games.Update(firstGame);
    db.Commit();
}

The game's name is not changed. The thing I'm struggling to understand is that the firstGame.Id is the same but the Insert inserts a new game with a new Id I would have thought LiteDb would process Update on the primary key?

It's likely a conceptual issue I'm misunderstanding.

0

There are 0 answers