MongoDB .NET在upsert上不生成_id

时间:2013-11-26 17:25:51

标签: c# mongodb mongodb-.net-driver

我正在尝试使用.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);

1 个答案:

答案 0 :(得分:20)

当然,我在发布问题后立即找到答案。从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; }
}