Při studiu zdrojových kódu knihovny Microsoft.AspNet.Identity.EntityFramework.dll jsem narazil na zápis, který mi připomněl novinku v Entity Frameworku 6.1 – možnost definovat entitám indexy, včetně těch unikátních.
Principiálně jde o použití data-annotation atributu [Index(„<index name>“, [isUnique: true|false])] na příslušné property, přičemž pokud je atribut se stejným názvem použit na více properties, vznikne index přes více sloupců (vlastností Order se řídí pořadí sloupců v definici indexu).
Ve FluentAPI lze takový efekt zapsat nepřímo, pomocí doplnění anotace:
this.Property(t => t.Identifier)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(
new IndexAttribute("UIDX_MonitoredApplication_Identifier") { IsUnique = true }));
UPDATE: Pokud chceme index přes více sloupců, nebo jeden sloupec zahrnout do více indexů, může kód vypadat takto:
Property(loginAccount => loginAccount.Email)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(
new IndexAttribute("UIDX_LoginAccount_Email_Deleted") { IsUnique = true, Order = 1 }));
Property(loginAccount => loginAccount.SingleSignOnIdentifier)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(
new IndexAttribute("UIDX_LoginAccount_SingleSignOnIdentifier_Deleted") { IsUnique = true, Order = 1 }));
Property(loginAccount => loginAccount.Deleted)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(new[]
{
new IndexAttribute("UIDX_LoginAccount_Email_Deleted") { IsUnique = true, Order = 2 },
new IndexAttribute("UIDX_LoginAccount_SingleSignOnIdentifier_Deleted") { IsUnique = true, Order = 2 }
}));