Skip to content

Instantly share code, notes, and snippets.

@rdingwall
Created March 1, 2012 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rdingwall/1950991 to your computer and use it in GitHub Desktop.
Save rdingwall/1950991 to your computer and use it in GitHub Desktop.
Raven DB unique constraint inserter
public interface IRavenUniqueInserter
{
void StoreUnique<T, TUnique>(
IDocumentSession session, T entity,
Expression<Func<T, TUnique>> keyProperty);
}
public class RavenUniqueInserter : IRavenUniqueInserter
{
public void StoreUnique<T, TUnique>(IDocumentSession session, T entity,
Expression<Func<T, TUnique>> keyProperty)
{
if (session == null) throw new ArgumentNullException("session");
if (keyProperty == null) throw new ArgumentNullException("keyProperty");
if (entity == null) throw new ArgumentNullException("entity");
var key = keyProperty.Compile().Invoke(entity).ToString();
var constraint = new UniqueConstraint
{
Type = typeof (T).Name,
Key = key
};
DoStore(session, entity, constraint);
}
static void DoStore<T>(IDocumentSession session, T entity,
UniqueConstraint constraint)
{
var previousSetting = session.Advanced.UseOptimisticConcurrency;
try
{
session.Advanced.UseOptimisticConcurrency = true;
session.Store(constraint,
String.Format("UniqueConstraints/{0}/{1}",
constraint.Type, constraint.Key));
session.Store(entity);
session.SaveChanges();
}
catch (ConcurrencyException)
{
// rollback changes so we can keep using the session
session.Advanced.Evict(entity);
session.Advanced.Evict(constraint);
throw;
}
finally
{
session.Advanced.UseOptimisticConcurrency = previousSetting;
}
}
}
using (var session = documentStore.OpenSession())
{
var person = new Person
{
EmailAddress = "rdingwall@gmail.com",
Name = "Richard Dingwall"
};
try
{
new RavenUniqueInserter().StoreUnique(session, person, p => p.EmailAddress);
}
catch (ConcurrencyException)
{
// email address already in use
...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment