public
Created

RavenDB Extension Method to generate an ID without storing the document

  • Download Gist
RavenExtensions.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public static string GenerateIdFor<T>(this IDocumentSession session)
{
// We need the advanced session in order to ensure that the keys are generated in the correct database.
// session.Advanced.DocumentStore.DatabaseCommands is not sufficient.
var advancedSession = session.Advanced as DocumentSession;
if (advancedSession == null)
throw new InvalidOperationException();
 
// An entity instance is required to generate a key, but we only have a type.
// In our case, the entities don't have public constructors so we must use reflection.
var entity = Activator.CreateInstance(typeof(T), true);
 
// Generate an ID using the commands and conventions from the current session
return advancedSession.Conventions.GenerateDocumentKey(advancedSession.DatabaseCommands, entity);
}

Usage: var id = session.GenerateIdFor();

Let's try that again (what, can't delete/edit a gist comment?)

Usage: var id = session.GenerateIdFor<Foo>();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.