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
public partial class User
{
public int Id { get; set; }
[Index(IsUnique = true)]
public virtual SharePoint SharePoint { get; set; }
}
When creating a migration for this code the following is being generated:
public override void Up()
{
CreateTable(
"dbo.Users",
c => new
{
Id = c.Int(nullable: false, identity: true),
SharePoint_Id = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.SharePoints", t => t.SharePoint_Id)
.Index(t => t.SharePoint_Id);
}
As you can see, the Index is not Unique here.
Also the DB Indices tell that the created index is not unique
I saw in older versions of EF that you had to do this via the Model Builder, which I tried aswell:
modelBuilder.Entity<Configuration>()
.Property(p => p.SharePoint)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute() { IsUnique = true }));
Which sadly results in the error:
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>)
So how is it possible to create a code-first migration, adding an Unique Index to a Column in EF 6.1?