I came across a requirement last week where users can associate additional email addresses to their account. Users will then have to confirm their additional email addresses. I added a new table in the database to accommodate this requirement. The table contains a PersonId column which is a foreign key to the Person table, an EmailAddress and EmailConfirmed columns.
I needed to create a unique filtered index on EmailAddress column where the email is confirmed. In Entity Framework 6, you can create an index for a column or across multiple columns by using the [Index] attribute.
i.e Single column index
public class Location { public int Id { get; set; } [Index] public string Code { get; set; } public int Name { get; set; } }
..or multiple columns index
public class Location { public int Id { get; set; } [Index("CodeAndName", 1, IsUnique = true)] public string Code { get; set; } [Index("CodeAndName", 2)] public int Name { get; set; } }
However, Entity Framework 6 does not support filtered index using the [Index] attribute. It has to be added manually during database migration. In my scenario, in the database migration file after executing add-migration, I would have to run a Sql script in the Up() method after the CreateTable to add the index and in Down() method to drop the index.
public partial class AddEmailAssociations : DbMigration { /// <inheritdoc /> public override void Up() { this.CreateTable( "dbo.EmailAssociation", c => new { Email = c.String(nullable: false, maxLength: 150), PersonId = c.String(nullable: false, maxLength: 128), EmailConfirmed = c.Boolean(nullable: false), }) .PrimaryKey(t => new { t.Email, t.PersonId }) .ForeignKey("dbo.Person", t => t.PersonId, cascadeDelete: true) .Index(t => t.PersonId); this.Sql("create unique nonclustered index IX_EmailAssociation_Email on dbo.EmailAssociation(Email) where EmailConfirmed = 1"); } /// <inheritdoc /> public override void Down() { this.DropForeignKey("dbo.EmailAssociation", "PersonId", "dbo.Person"); this.DropIndex("dbo.EmailAssociation", new[] { "PersonId" }); this.DropIndex("dbo.EmailAssociation", "IX_EmailAssociation_Email"); this.DropTable("dbo.EmailAssociation"); } }