Caution

This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.

Note

This article uses EF 7.0.0-rc1 which is the latest pre-release available on NuGet.org. You can find nightly builds of the EF7 code base hosted on https://www.myget.org/F/aspnetvnext/ but we do not maintain up-to-date documentation for nightly builds.

Note

The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared EntityFramework.Relational package).

Alternate Keys (Unique Constraints)

A unique constraint is introduced for each alternate key in the model.

Conventions

By convention, the index and constraint that are introduced for an alternate key will be named AK_<type name>_<property name>. For composite alternate keys <property name> becomes an underscore separated list of property names.

Data Annotations

Unique constraints can not be configured using Data Annotations.

Fluent API

You can use the Fluent API to configure the index and constraint name for an alternate key.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
    class MyContext : DbContext
    {
        public DbSet<Car> Cars { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Car>()
                .HasAlternateKey(c => c.LicensePlate)
                .HasName("AlteranteKey_LicensePlate");
        }
    }

    class Car
    {
        public int CarId { get; set; }
        public string LicensePlate { get; set; }
        public string Make { get; set; }
        public string Model { get; set; }