Generate compound unique constraint / index in EF Core

I need a complex unique constraint for my Name object, which is unique to Category (for which it has FK).

So something like this:

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

But this fails when I generate the migration due to the Category.Id navigation property.

I know that I can encode values ​​as strings, but I do not want to lose static typing.

What options do I have?

+5
source share
2 answers

Add a foreign key for the CategoryId category in the object in question and use it in the index builder instead of the navigation property.

+5
source

Once you recognize the name of the shadow property, you can use (at least in EF Core 1.1.0) the HasIndex method based on overload

 public virtual IndexBuilder HasIndex(params string[] propertyNames) 

eg.

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

Same for HasAlternateKey :

 entityTypeBuilder .HasAlternateKey("Name", "CategoryId" }); 
+3
source

Source: https://habr.com/ru/post/1260218/


All Articles