Reputation: 5389
strangely I couldn't find any example or mention of this anywhere. I would like to set indexes on two of my columns (not a composite index, just two separate indexes) using the fluent api.
For example, I was wondering if it's possible to do something like:
modelBuilder.Entity<T>
.HasIndex(h => h.Column1)
.HasIndex(h => h.Column2);
However, from the looks of it, it's not possible to chain indexes like this. Currently what I'm doing is setting them separately like:
modelBuilder.Entity<T>
.HasIndex(h => h.Column1)
modelBuilder.Entity<T>
.HasIndex(h => h.Column2)
Is there a better way to do this?
Upvotes: 5
Views: 8452
Reputation: 32069
In Entity Framework 6.x
you can create indexes using both Data Annotation
and Fluent API
but in EF Core
according to EF Core Indexes documentation, so far, you can only create indexes with Fluent API
. So what you are doing is the appropriate way of doing this in EF Core
.
Additionally one thing you can do is separate your Entity Configuration from DbContext
as follows:
public class FooConfiguration : IEntityTypeConfiguration<Foo>
{
public void Configure(EntityTypeBuilder<Foo> builder)
{
...
builder.HasIndex(h => h.Column1).IsUnique();
builder.HasIndex(h => h.Column2).IsUnique();
..
}
}
Then apply the configuration in OnModelCreating
method as follows:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new FooConfiguration()); //<-- add here
}
Upvotes: 3
Reputation: 1527
HasIndex() returns a type of IndexBuilder which allows you to call things like .IsUnique() or .HasName() etc.
Is there a better way to do this?
Depends if you consider this better or not, and if you REALLY want to be fluent.
To keep adding indexes using a fluent style you need to get back to the EntityTypeBuilder. If you really wanted you could use an extension method.
modelBuilder.Entity<T>
.AddIndex(h => h.Column1)
.AddIndex(h => h.Column2);
public static EntityTypeBuilder<TEntity> AddIndex<TEntity>(this EntityTypeBuilder<TEntity> builder, Expression<Func<TEntity, object>> indexExpression) where TEntity : class
{
builder.HasIndex(indexExpression);
return builder;
}
Or
builder.Entity<T>()
.AddIndex(indexBuilder => indexBuilder.HasIndex(h => h.Column1))
.AddIndex(indexBuilder => indexBuilder.HasIndex(h => h.Column2).IsUnique());
public static EntityTypeBuilder<TEntity> AddIndex<TEntity>(this EntityTypeBuilder<TEntity> builder, Action<EntityTypeBuilder<TEntity>> action) where TEntity : class
{
action(builder);
return builder;
}
Upvotes: 6