I have a column "Name" that must be unqiue. No foreign key or anything like that.
EF 6.1 finally supports creating such indexes via Annotations. That has been discussed already on SO. But it seems it can only be done via annotations in the classes. How do I do that using only the Fluent API?
Something like this:
public class PersonConfiguration : EntityTypeConfiguration<Person> { public PersonConfiguration() { HasKey(p => p.Id); Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); //not possible? Index(p => p.Name).IsUnique(); //??? } }
The Entity Framework Core Fluent API HasIndex method is used to create a database index on the column mapped to the specified entity property. By default, indexes are created for foreign keys and alternate keys.
Data annotations and the fluent API can be used together, but Code First gives precedence to Fluent API > data annotations > default conventions. Fluent API is another way to configure your domain classes.
Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.
NOTE: Relevant to EF 6
You can use IndexAttribute
as mentioned but with Fluent API
instead of DataAnnotations
which will do the trick:
modelBuilder .Entity<Person>() .Property(t => t.Name) .HasColumnAnnotation( "Index", new IndexAnnotation(new IndexAttribute("IX_Name") { IsUnique = true }));
Unfortunately there is no other way to create unique indexes using Fluent API
. There is an open issue regarding this feature: Unique Constraints (Unique Indexes)
Fluent API
to specify indexes without additional tricks. HasIndex
allows to define it: modelBuilder .Entity<Person>() .HasIndex(x => x.Name);
Hence it returs IndexBuilder
object you can use it for further index configurations (i.e uniqueness):
modelBuilder .Entity<Person>() .HasIndex(x => x.Name) .IsUnique();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With