Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 934
Dan Avatar asked Sep 13 '25 00:09

Dan


1 Answers

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();
    });
like image 84
vivek nuna Avatar answered Sep 14 '25 15:09

vivek nuna