EF Core Fluent API - unique constraint not being detected/included in migration

c# ef-fluent-api entity-framework-core sql-server

Question

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!

1
1
8/17/2018 2:51:57 PM

Popular Answer

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();
    });
1
8/17/2018 3:47:44 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow