2013-11-26 42 views
9

我試圖使用.NET驅動程序將文檔插入MongoDB 2.4.4。它似乎不會自動生成_id upserts,雖然它確實生成了簡單插入上的_id。我怎樣才能讓驅動程序正確生成_idMongoDB .NET不會在upsert上生成_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); 
+0

我很好奇downvote是什麼?由於有人剛剛通過並且低估了我自己回答的其他兩個問題,我只想指出這實際上是StackOverflow的一項完全支持的功能。在「提問」表格中甚至有一個「回答你自己的問題 - 分享你的知識問答風格」複選框。 –

+0

Karma恢復。這是一個有用的問題,並提供有用的答案。 – RobD

+0

哈,謝謝@RobD :) –

回答

17

當然,我發現問題後立即找到答案。從this answer,解決方案是將[BsonIgnoreIfDefault]屬性添加到ID。在這個問題的例子是:

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; } 
}