Search code examples
c#indexingentity-framework-corekeyrelational-database

What's the real difference between Alternate Key and HasIndex with uniqueness in EF core?


I'm intrested in what is the real difference between this

e.HasIndex(c => new { c.UserId, c.ApplicationId, c.Value }).IsUnique();

and this

e.HasAlternateKey(c => new { c.UserId, c.ApplicationId, c.Value });

in EF core fluent api configuration.

The use-case here is that we have a PK called Id then we have a secondary(alternate key) which is a composite key which is built from the following attributes: UserID ApplicationId and Value. The only thing i found about my question is the following quote from here: https://www.learnentityframeworkcore.com/configuration/fluent-api/hasindex-method

"While similar in most practical aspects, this is not the same as creating a unique constraint on the column, which can be achieved by creating an alternate key on the property."

I dont really get the concept of this difference and i also don't know the difference between a unique constraint and a unique index.

If somone could explain the definitions(and the difference between them) to me i would be really grateful.


Solution

  • From the official documentation:

    If you just want to enforce uniqueness on a column, define a unique index rather than an alternate key (see Indexes). In EF, alternate keys are read-only and provide additional semantics over unique indexes because they can be used as the target of a foreign key.

    In other words - both create a unique index, but the alternate key has some additional properties (e.g. can be used as the target of a foreign key)