title: EF Code-First Add Unique Index to Column
body: <p>In my Entity-Framework Code-First Model I have a Table that needs one column to have unique values. I want to apply an Unique Index to it as I saw that it is very easy in EF 6.1</p>
  
  <pre><code>public partial class User
  {
     public int Id { get; set; }
  
     [Index(IsUnique = true)]
     public virtual SharePoint SharePoint { get; set; }
  }
  </code></pre>
  
  <p>When creating a migration for this code the following is being generated:</p>
  
  <pre><code>public override void Up()
  {
      CreateTable(
          "dbo.Users",
          c =&gt; new
              {
                  Id = c.Int(nullable: false, identity: true),
                  SharePoint_Id = c.Int(nullable: false),
              })
          .PrimaryKey(t =&gt; t.Id)
          .ForeignKey("dbo.SharePoints", t =&gt; t.SharePoint_Id)
          .Index(t =&gt; t.SharePoint_Id);
  }
  </code></pre>
  
  <p>As you can see, the Index is <strong>not</strong> Unique here.</p>
  
  <p>Also the DB Indices tell that the created index is not unique</p>
  
  <p><img src="https://i.stack.imgur.com/StJp8.png" alt="None Unique SQL Index"></p>
  
  <p>I saw in older versions of EF that you had to do this via the Model Builder, which I tried aswell:</p>
  
  <pre><code>modelBuilder.Entity&lt;Configuration&gt;()
      .Property(p =&gt; p.SharePoint)
      .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute() { IsUnique = true }));
  </code></pre>
  
  <p>Which sadly results in the error: </p>
  
  <blockquote>
    <p>The type 'kData.Sharepoint' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Data.Entity.ModelConfiguration.Configuration.StructuralTypeConfiguration.Property (System.Linq.Expressions.Expression>)</p>
  </blockquote>
  
  <p>So how is it possible to create a code-first migration, adding an Unique Index to a Column in EF 6.1?</p>