I am trying to add a unique constraint on two columns. I found multiple sources declaring that I should be using HasAlternateKey method for EF Core Fluent API applications. However, after running Add-Migration, the code that is generated in the migration files does not include the constraint - almost as if its being purposely ignored or not detected.
Here is the ModelBuilder code that I am using:
        modelBuilder.Entity<PlasmidStockCode>(e =>
        {
            e.ToTable("PlasmidStockCode");
            e.HasKey(c => c.ID);
            e.Property(c => c.ID).ValueGeneratedOnAdd();
            e.HasAlternateKey(c => new { c.ClientName, c.PlasmidName });
            e.HasMany(c => c.PlasmidStockComments).WithOne().HasForeignKey(c => c.PlasmidStockCodeID).OnDelete(DeleteBehavior.Restrict);
            e.HasMany(c => c.PlasmidStockLots).WithOne().HasForeignKey(c => c.PlasmidStockCodeID).OnDelete(DeleteBehavior.Restrict);
            e.HasMany(c => c.qPCRTargets).WithOne().HasForeignKey(c => c.PlasmidStockCodeID).OnDelete(DeleteBehavior.Restrict);
        });
        AddBaseConfiguration(modelBuilder);
    }
I've also attempted to use .HasIndex, but unfortunately, is not being detected/included either.
Any idea as to what I may be missing? Thanks in advance!
Use IsUnique and HasIndex methods in you DBContext class's OnModelCreating method to add the composite key to your table. Then add migration using Add-Migration <YourMigrationName> and then run Update-Database in Program Manager Console. 
modelBuilder.Entity<PlasmidStockCode>(b =>
    {
        b.HasIndex(e => (new { e.ClientName, e.PlasmidName })).IsUnique();
    });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With