title: Unique Constraint in Entity Framework Code First
body: <p><strong>Question</strong></p>
  
  <p>Is it possible to define a unique constraint on a property using either the fluent syntax or an attribute? If not, what are the workarounds?</p>
  
  <p>I have a user class with a primary key, but I would like to make sure the email address is also unique. Is this possible without editing the database directly?</p>
  
  <p><strong>Solution (based on Matt's answer)</strong></p>
  
  <pre><code>public class MyContext : DbContext {
      public DbSet&lt;User&gt; Users { get; set; }
  
      public override int SaveChanges() {
          foreach (var item in ChangeTracker.Entries&lt;IModel&gt;())
              item.Entity.Modified = DateTime.Now;
  
          return base.SaveChanges();
      }
  
      public class Initializer : IDatabaseInitializer&lt;MyContext&gt; {
          public void InitializeDatabase(MyContext context) {
              if (context.Database.Exists() &amp;&amp; !context.Database.CompatibleWithModel(false))
                  context.Database.Delete();
  
              if (!context.Database.Exists()) {
                  context.Database.Create();
                  context.Database.ExecuteSqlCommand("alter table Users add constraint UniqueUserEmail unique (Email)");
              }
          }
      }
  }
  </code></pre>