Skip to content

Instantly share code, notes, and snippets.

@mattjohnsonpint
Created October 2, 2012 21:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattjohnsonpint/3823390 to your computer and use it in GitHub Desktop.
Save mattjohnsonpint/3823390 to your computer and use it in GitHub Desktop.
RavenDB Extension Method to generate an ID without storing the document
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);
}
@mattjohnsonpint
Copy link
Author

Usage: var id = session.GenerateIdFor();

@mattjohnsonpint
Copy link
Author

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

Usage: var id = session.GenerateIdFor();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment