Yoann. B
Yoann. B

Reputation: 11143

How-To get consecutive id with RavenDb default id generator

I'm evaluating RavenDB for a new project.

If i create 100 entities i got great consecutive ids like :

But if i build a new DocumentStore instance (after App Restart) and try to create new entities i got strange ids like this :

Any help ?

Note : I'm using Embedded Server with ASP.NET MVC 3

Upvotes: 6

Views: 1802

Answers (4)

Tomas
Tomas

Reputation: 379

You can set an identifier by your client, while still relying on the server to generate the identifier for you. It is done using the NextIdentityForCommand command:

var command = new NextIdentityForCommand("<<your collection name>>");
Session.Advanced.RequestExecutor.Execute(command, Session.Advanced.Context);
var id = command.Result;

This way you can use the identity value even in different field from Id. On the other hand, this makes creating a document slower, because you have to approach a server twice.

Upvotes: 0

Pure.Krome
Pure.Krome

Reputation: 86957

From the RavenDb documents, you're after the Identity strategy.

RavenDB also supports the notion of Identity, for example if you need IDs to be consecutive. By creating a string Id property in your entity, and setting it to a value ending with a slash (/), you can tell RavenDB to use that as a key perfix for your entity. That prefix followed by the next available integer ID for it will be your entity's ID after you call SaveChanges().

eg.

var foo = new Foo();
foo.Id = "foo/"; // <-- this will use the Identity strategy, not HiLo.

session.Store(foo);
session.SaveChanges();

Upvotes: 7

synhershko
synhershko

Reputation: 4492

This is by design - new HiLo keys are generated whenever you create a DocumentStore instance, so the gaps you are seeing are the unused ids from the other session.

Why do you care for consecutive ids?

This may be a good read on the subject, too: http://groups.google.com/group/ravendb/browse_thread/thread/3dbcacbc8b366ff8/

Upvotes: 8

Ayende Rahien
Ayende Rahien

Reputation: 22956

You might want to look at the identity option for RavenDB, but that isn't really something that you should care about.

Upvotes: 3

Related Questions