EF Core 1.1 generating unique index on FK one-to-one

.net-core entity-framework-core

Question

I'm using EF Core 1.1 and created my one-to-one relationships, an example:

EntityTypeBuilder<Account>
   .HasOne(a => a.Customer)
   .WithOne(a => a.Account)
   .HasForeignKey<Account>(a => a.CustomerId)

Now using Add-Migration on my DbContext it generates the following:

migrationBuilder.CreateIndex(
   name: "IX_Accounts_CustomerId",
   table: "Accounts",
   column: "CustomerId",
   unique: true);

Is there a way to specify in Fluent to remove the uniqueness from the index? I don't mind the index being generated, but for my purposes it can not be unique. The reason is that these tables are auditable so there can be duplicate data (outside of the PK). Hence records can contain the same FK id if there were no changes to that FK entity (but maybe changes elsewhere in the record).

TL;DR Any way of making the index non-unique in Fluent for one-to-one FKs?

1
1
12/15/2016 5:46:42 PM

Popular Answer

If you want to make the index backing the foreign key non-unique, you need to configure the index on FK property in fluent api and set it to be non-unique. In you example adding following line of code in OnModelCreating() method will give you desired result.

modelBuilder.Entity<Account>().HasIndex(e => e.CustomerId).IsUnique(false);

Though having duplicate values in FK property for one-to-one relationship can have undesired implications at runtime while fixing up navigation properties.

2
12/15/2016 8:50:25 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