Define an Entity with a Unique Key at the Model Level

asp.net-core asp.net-core-mvc c# entity-framework-core

Question

Using asp.net 5 entity framework 7, I would like to define a field with a unique key constraint at the model level. I am not talking about a primary key. I believe in EF 6 it used to be something like this:

    [Key]
    public int Id{ get; set; }

    [Index("IX_UserName", 1, IsUnique = true)]
    public string UserName {get; set;}

Accepted Answer

You can configure this in the OnModelCreating override. See http://ef.readthedocs.org/en/latest/modeling/configuring.html#indexes

Example:

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Index(b => b.Url)
            .Unique();
    }
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why