Unique key with EF code first

Prashant Cholachagudda picture Prashant Cholachagudda · Apr 18, 2011 · Viewed 76.4k times · Source

I have a following model in my project

public class Category
{   
    public Guid ID { get; set; }
    [Required(ErrorMessage = "Title cannot be empty")]
    public string Title { get; set; }
}

and I'm trying to make Title as unique key, I googled for the solution, but couldn't find any. Can any suggest me how to do it, please?

Answer

Ladislav Mrnka picture Ladislav Mrnka · Apr 18, 2011

Unfortunately you can't define it as unique key in code first because EF doesn't support unique keys at all (it is hopefully planned for next major release). What you can do is to create custom database intializer and add unique index manually by calling SQL command:

public class MyInitializer : CreateDatabaseIfNotExists<MyContext>
{
  protected override void Seed(MyContext context)
  {
    context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX IX_Category_Title ON Categories (Title)");
  }
}

And you must set this initializer in the bootstrap of your application.

Database.SetInitializer<MyContext>(new MyInitializer());

Edit

Now (EF 6.1 onwards )you can easily have unique constrains ,

[Index("TitleIndex", IsUnique = true)]
 public string Title { get; set; }