Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RavenDB get ID of newly stored document

Tags:

c#

ravendb

I started playing around with RavenDB (which really looks great so far). However I'm stuck trying the following.

I store a new document like so

Product p = new Product() { Title = "My Fancy Product" };
RavenSession.Store(p);

Now I would like to get the Id of the newly stored document. Who can this be done? Just to access p.Id after the store doesn't seem to work ...

Thanks in advance!

like image 616
Dänu Avatar asked Dec 26 '22 21:12

Dänu


1 Answers

The Id property of the Product class must be of type string instead of integer.

Then you will be able to retrieve the autogenerated id after the operation:

Product p = new Product() { Title = "My Fancy Product" };
RavenSession.Store(p);
string id = p.Id;

More information can be found in the documentation (Document IDs section):

In the example above we had a string Id property for BlogPost, and left it blank. It is this property that will be used as the "primary key" for this document. Note how RavenDB generated an ID for us, "BlogPosts/1", based on the default convention which we will discuss in a second.

If there is no Id property on a document, RavenDB will still generate a unique ID, but it will be retrievable only by calling session.Advanced.GetDocumentId(object). In other words, having an Id property is entirely optional, so you can explicitly define such a property only when you need this information to be more accessible.

like image 115
Darin Dimitrov Avatar answered Dec 31 '22 04:12

Darin Dimitrov