I have a document of type A and one property is a collection of classes of type B. B has an integer Id property and the only restriction is that it has to be unique within that Raven database. The Raven client is a Web API web application (C#) that runs on a single physical server. The server could be dealing with multiple requests simultaneously and so there could be multiple threads all trying to get a new ID.
In Raven then is it possible to generate a unique value for the B.Id property? In reality then I will get a new ID for each B instance in the collection.
The way that I had considered to do it is as follows:
- Store an IDInfo document in Raven with a LastValue (int) property to store the last generated B.ID value.
- Have a generic ID generator class that would have a function GetNewIDs<T>(int numberOfIds) that could provide N new B.ID values using the IDInfo document. It would load the document, increment LastValue, call IDocumentSession.SaveChanges and then return a collection of IDs.
- Ensure that IDs are not duplicated by serializing access to GetNewIDs using a machine wide mutex. This obviously has issues if the web app is running on multiple machines simultaneously. E.g. A Dev running the Web API source code also.
Is this the best way to do it? Can it be done within a transaction?