我试着做这样的事情:
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"));
但是,正如代码中提到的,我收到了以下错误:LiteDB.LiteException:‘无法在唯一索引'a’中插入重复键。重复的值是‘a’.‘’
如果存在Upsert用于插入或更新,不是吗?
发布于 2018-01-29 08:15:59
是StringPair
类包含唯一Id属性(_id
字段)。LiteDB使用PK索引(_id
字段)检查是否存在文档、做插入或更新。试试这个类结构:
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
发布于 2020-09-07 02:28:32
如果您告诉LiteDb引擎应该将类的哪些属性视为id,则可以很容易地保持类的结构,并在其上使用属性BsonIdAttribute
:
public sealed class StringPair
{
[BsonId]
public string First { get; set; }
public string Second { get; set; }
}
https://stackoverflow.com/questions/48486498
复制相似问题