Home
Options

Using LinqPad7 with Litedb file - connection errors - solution

I realize LiteDB is not a "mainstream" db option, so it is unsurprising that I could not find any help on Google, so take this complaint with a "grain of salt:.

If you create a connection (to a LiteDB file) to do your work and run a C# program (may experience the same problem with other query options, haven't tried it), you get the error message:

IOException: The process cannot access the file 'D:_temp\filename_.db' because it is being used by another process.

If you specify Read Only on the preconfigured connection then the code works (as long as you do not try to update anything).

If you do not use a preconfigured connection, the code works, even for updates.

So, it "works", but just a little differently than I accustomed to.

static void Main()
{
List ids = new();
using (var db = new LiteDatabase(@D:\temp\ImageCatalog.db))
{
try
{
var queryResult = db.GetCollection("PhotoBase")
.Find(pb => pb.GeoLocation == null)
.Take(10)
.ToList();

        ids = queryResult.Select(r => r.Id).ToList();
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
}
using (var db = new LiteDatabase(@"D:\temp\ImageCatalog.db"))
{
    var photos = db.GetCollection<PhotoBase>("PhotoBase");
    foreach (var id in ids)
    {
        var rec = db.GetCollection<PhotoBase>("PhotoBase")
                    .Find(pb => pb.Id == id)
                    .FirstOrDefault();
        if (rec != null)
        {
            rec.GeoLocation = new  GeoLocation {Altitude = 1, Latitude = 1.2F, Longitude = 4.5F };
            var rslt = photos.Update(rec);
            if (!rslt)
            {
                Console.WriteLine($"Failed to update record with ID: {id}");
            }
        }
    }
    db.Commit();
}

}

Sign In or Register to comment.