Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

say I have a product listing. When I add a new product I save it using something like

var doc=products.Insert<ProductPDO>(p);

The problem is that I want after this is done to redirect the user to the page with the product. So I need to redirect to say /products/<ObjectID>

However, I see no way of getting the ObjectID right afterwards without manually querying the database and look for a document with all the same fields and such.

Is there an easier way? (also, doc in this instance returns null for some reason)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
346 views
Welcome To Ask or Share your Answers For Others

1 Answer

The Insert method automatically sets the property that is declared as the BSON ID of the model.

If declared as follows...

[BsonId]
public ObjectId Id { get; set; }

... then the Id field will contain the default (new, unique) BSON ID of the object after inserting the object into a collection:

coll.Insert(obj);
// obj.Id is now the BSON ID of the object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...