Senior
How to set up an index for a new query? How to create a composite index with multiple conditions?
sobes.tech AI
Answer from AI
In C#, Entity Framework (EF) or EF Core is usually used to configure indexes. To create an index for a new query, you need to define the index at the data model level.
To create a simple index in EF Core, you can use an attribute or Fluent API:
// Attribute
[Index(nameof(PropertyName))]
public class MyEntity
{
public int Id { get; set; }
public string PropertyName { get; set; }
}
For a composite index (multiple properties):
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>()
.HasIndex(e => new { e.Property1, e.Property2 });
}
This will create a composite index on Property1 and Property2, which will speed up queries with conditions on these fields.
Important: indexes should be created considering actual queries to avoid unnecessary load on data writing and storage.