MongoDB的.NET不产生对UPSERT _id

问题描述 投票:12回答:1

我试图UPSERT文档到MongoDB的2.4.4使用.NET驱动程序。这似乎不是自动生成的upserts的_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);
c# mongodb mongodb-.net-driver
1个回答
20
投票

当然,我张贴的问题后,立即找到答案。从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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.