Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a composite unique constraint/index, in EF Core

I need a composite unique constraint for my entity's Name property, which is unique per Category (for which it has an FK).

So something like this:

entityTypeBuilder
  .HasIndex(i => new { i.Name, i.Category.Id })
  .IsUnique();

But this fails when I generate a migration, because of the Category.Id navigation property.

I know I can hardcode the values as strings, but I don't want to lose the static typing.

What options do I have?

like image 527
grokky Avatar asked Nov 23 '16 15:11

grokky


People also ask

How do I create a composite key in Entity Framework Core?

You can also configure multiple properties to be the key of an entity - this is known as a composite key. Composite keys can only be configured using the Fluent API; conventions will never set up a composite key, and you can not use Data Annotations to configure one.

What is composite unique index?

A composite unique key is a unique key made up of a combination of columns. Oracle creates an index on the columns of a unique key, so a composite unique key can contain a maximum of 16 columns. To define a composite unique key, you must use table_constraint syntax rather than column_constraint syntax.

Does EF core use indexes?

EF Core only supports one index per distinct set of properties. If you configure an index on a set of properties that already has an index defined, either by convention or previous configuration, then you will be changing the definition of that index.


2 Answers

As soon as you know the shadow property name, you can use (at least in EF Core 1.1.0) the string based HasIndex method overload

public virtual IndexBuilder HasIndex(params string[] propertyNames)

e.g.

entityTypeBuilder
  .HasIndex("Name", "CategoryId")
  .IsUnique();

Same for HasAlternateKey:

entityTypeBuilder
  .HasAlternateKey("Name", "CategoryId");
like image 184
Ivan Stoev Avatar answered Sep 18 '22 13:09

Ivan Stoev


Add a foreign key for Category of CategoryId on the entity in question and use that in the index builder instead of the navigation property.

like image 33
steamrolla Avatar answered Sep 20 '22 13:09

steamrolla