Define an entity with a unique key at the model level

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 the primary key. In EF 6, I believe it was something like this:

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

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

      

+3


source to share


1 answer


You can customize this in the override OnModelCreating

. 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();
    }
}

      

+2


source







All Articles