2013-11-26 20 views
9

Bir sürücüyü, .NET sürücüsünü kullanarak MongoDB 2.4.4'e yükseltmeye çalışıyorum. Düz ekler üzerinde _id doğru şekilde üretmesine rağmen, otomatik olarak _id'u upserts oluşturmaz. Sürücünün _id düzgün şekilde nasıl üretmesine neden olabilirim?MongoDB .NET, ups'de _id üretmiyor

Sorunu gösteren küçük bir örnek.

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

İndirgemenin ne için olduğunu merak ediyorum. Birisi sadece kendime cevap verdiğim iki sorudan daha azını aştı ve reddettiğinden, bunun aslında StackOverflow'un tam olarak desteklenen bir özelliği olduğuna dikkat çekeceğim. Hatta "Bir soru sorun" formunda "Kendi sorunuzu yanıtlayın - Bilgi Soru ve Cevap stilinizi paylaşın" için bir onay kutusu bile var. –

+0

Karma geri yüklendi. Bu yararlı bir cevap ile yararlı bir sorudur. – RobD

+0

Ha, teşekkürler @RobD :) –

cevap

17

Ve tabiki cevabı, soruyu gönderdikten hemen sonra buluyorum. this answer'dan çözüm, kimliğe [BsonIgnoreIfDefault] özniteliği eklemektir. Sorudan örnekte şu olabilir:

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