Search code examples
ravendbravendb-studio

Several unique constrains on a single document in RavenDb


Let's say I have a class:

public class Person
{
   public string Name{get;set;}
   public string Email {get;set;}
   public string GoogleId {get;set;}
   public string FacebookId {get;set;}
}

If I want to make the email unique I will use the unique constraint bundle.

But I want to make both the googleId and the facebookId properties as a single unique constraint side by side with the email constraint (while non of them is the id). Is it possible?


Solution

  • Use the UniqueConstraints bundle:

    public class Person
    {
       public string Name {get;set;}
       [UniqueConstraint]
       public string Email {get;set;}
       public string GoogleId {get;set;}
       public string FacebookId {get;set;}
       [UniqueConstraint]
       public string GoogleAndFacebookIds { get;set; }
    }
    

    Just make sure you update GoogleAndFacebookIds everytime you update either GoogleId or FacebookId. I was doing this so much I ended up using a simple interface on all my classes that did this sort of thing:

    public interface ICombinedConstraints
    {
        string UniqueId { get; set; }
        void UpdateConstraints();
    }
    

    So,

    public class Person : ICombinedConstraints
    {
        public string Name{get;set;}
        [UniqueConstraint]
        public string Email {get;set;}
        public string GoogleId {get;set;}
        public string FacebookId {get;set;}
        [UniqueConstraint]
        public string UniqueId { get; set; }
    
        public void UpdateConstraints()
        {
            UniqueId = GoogleId + FacebookId;
        }
    }