Created
March 1, 2012 16:22
-
-
Save rdingwall/1950991 to your computer and use it in GitHub Desktop.
Raven DB unique constraint inserter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using (var session = documentStore.OpenSession()) | |
{ | |
var person = new Person | |
{ | |
EmailAddress = "[email protected]", | |
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