2013-11-26 14 views
9

.NETドライバを使用してMongoDB 2.4.4に文書をアップしようとしています。プレーン・インサートで_idが正しく生成されますが、アップ・サートでは_idが自動的に生成されないようです。ドライバで_idを正しく生成させるにはどうすればよいですか?MongoDB .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が何であったか興味がありますか?誰かがちょうど私が自分自身に答えた2つの他の質問を通過してdownvotedので、私はそれが実際にStackOverflowの完全にサポートされている機能であることを指摘します。 「Ask a question」フォームには、「あなた自身の質問に答える - あなたの知識のQ&Aスタイルを共有する」チェックボックスもあります。 –

+0

カルマが復元されました。これは有益な質問で有益な答えです。 – RobD

+0

Ha、ありがとう@RobD :) –

答えて

17

もちろん、質問を投稿した直後に回答が見つかります。 this answerから、解決策は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; } 
} 
関連する問題