[英]MongoDB .NET not generating _id on upsert
我正在嘗試使用.NET驅動程序將文檔插入MongoDB 2.4.4。 似乎不會在upsert上自動生成_id
,盡管它在普通插入上正確生成了_id
。 如何讓驅動程序正確生成_id
?
這是一個演示問題的小例子。
public class MongoObject
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
[BsonRepresentation(BsonType.ObjectId)]
public string MongoID { get; set; }
public int Index { get; set; }
}
var obj = new MongoObject()
{
Index = 1
};
//This inserts the document, but with a _id set to Null
_collection.Update(Query.EQ("Index", BsonValue.Create(1)), Update.Replace(obj), UpdateFlags.Upsert, new WriteConcern() { Journal = true });
//This inserts the document with the expected autogenerated _id
//_collection.Insert(obj);
當然,我在發布問題后立即找到答案。 從這個答案來看,解決方案是在ID中添加[BsonIgnoreIfDefault]
屬性。 在問題的例子中它將是:
public class MongoObject
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
[BsonRepresentation(BsonType.ObjectId)]
[BsonIgnoreIfDefault] // <--- this is what was missing
public string MongoID { get; set; }
public int Index { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.