1

I am trying to do something like this :

db = new LiteDatabase(@"albumdata.db");
db_string = db.GetCollection<StringPair>("strings");
db.Engine.EnsureIndex("strings", "a", true);

db_string.Upsert(new StringPair("a", "1"));
// this line throws this exception : LiteDB.LiteException: 'Cannot insert duplicate key in unique index 'a'. The duplicate value is '"a"'.'
db_string.Upsert(new StringPair("a", "1"));

But as mentioned in code I receive this error : LiteDB.LiteException: 'Cannot insert duplicate key in unique index 'a'. The duplicate value is '"a"'.'

Isn't Upsert for insert or update if it exists?

AVEbrahimi
  • 17,993
  • 23
  • 107
  • 210

2 Answers2

2

Is your StringPair class contains an unique Id property (_id field). LiteDB uses PK index (_id field) for check if exists document do insert or update. Try this class structure:

public class StringPair
{
    public StringPair(string a, string b)
    {
        this.Id = a;
        this.OtherField = b;
    }

    public StringPair()
    {
        // don't forgot parameterless ctor
    }

    // Define "Id" or use [BsonId] in your property or use FluentApi mapper

    public string Id { get; set; }
    public string OtherField { get; set; }
}


db = new LiteDatabase(@"albumdata.db");

db_string = db.GetCollection<StringPair>("strings");

// PK already contains unique index
// db.Engine.EnsureIndex("strings", "a", true);

db_string.Upsert(new StringPair("a", "1")); // insert

db_string.Upsert(new StringPair("a", "2")); // update
mbdavid
  • 1,076
  • 7
  • 8
0

You can easily keep your class structure if you tell LiteDb engine what property of you class should be treated as id, using attribute BsonIdAttribute on it:

public sealed class StringPair
{
    [BsonId]
    public string First { get; set; }
    public string Second { get; set; }
}
AndrIV
  • 171
  • 2
  • 7