Search code examples
entity-frameworkef-fluent-apidb-first

What is the benefit of adding .HasIndex() in your mappings, on a DBFirst scenario?


I have been searching on EF Core documentation, if adding .HasIndex() on your entities mappings would bring any benefits on a DbFirst scenario, and I couldn`t find anything.

I have this 20yo DB that has all the necessary tables and indexes created, and I am mapping some tables to query them using EF Core. I wonder, what could be the benefits of mapping the indexes on a DbFirst scenario where you would never update the tables schema via code? Does it affect the way EF generates the SQL queries?


Solution

  • None. HasIndex would only apply to creating indexes for code-first/migrations. You don't need to map indexes for EF to generate or optimize the query.

    I do recommend after introducing EF to a project to record/report on the most common queries executed to determine whether there are new indexes or adjustments to existing indexes that might benefit your application's performance. (I.e. included columns)