Entity Framework Indexing ALL foreign key columns

后端 未结 2 538
礼貌的吻别
礼貌的吻别 2020-12-20 16:53

This may be too much of an opinion-based question but here goes:

I\'ve found an interesting quirk with Entity Framework and database migrations. It seems that whene

相关标签:
2条回答
  • 2020-12-20 17:28

    Short answer. No.

    To expand slightly, at the database create time, entity framework does not know how many records each table or entity will have, nor does it know how the entities will be queried.

    *In my opinion * the creation of a foreign key is more likely to be right than wrong, I had massive performance issues using a different ORM which took longer to diagnose because I thought I had read in the documentation that it behaved the same way.

    You can check the Sql statement that EF produces and run it manually if you want to double check.

    You know your data better than EF does, and it should work just fine if you drop the index manually.

    IIRC you can create 1 way navigation properties if you use the right naming convention, although this was some time ago, and I never checked whether the index was created.

    0 讨论(0)
  • 2020-12-20 17:42

    In EF Code First, the general reason why you would model a foreign key relationship is for navigability between entities. Consider a simple scenario of Country and City, with eager loading defined for the following LINQ statement:

    var someQuery = 
       db.Countries
         .Include(co => co.City)
         .Where(co => co.Name == "Japan")
         .Select(...);
    

    This would result in a query along the lines of:

    SELECT *
    FROM Country co
    INNER JOIN City ci
      ON ci.CountryId = co.ID
    WHERE co.Name = 'Japan';
    

    Without an Index on the foreign key on City.CountryId, SQL will need to scan the Cities table in order to filter the cities for the Country during a JOIN.

    TL;DR

    Indexes on Foreign Keys are recommended, even if you don't filter directly on the foreign key, it will still be needed in Joins. The exceptions to this seem to be quite contrived:

    • If the selectivity of the foreign key is very low, e.g. in the above scenario, if 50% of ALL cities in the countries table were in Japan, then the Index would not be useful.

    • If you don't actually ever navigate across the relationship.

    One additional optimization consideration is whether to use the foreign key in the Clustered Index of the child table (i.e. cluster Cities by Country). This is often beneficial in parent : child table relationships where it is common place to retrieve all child rows for the parent simultaneously.

    0 讨论(0)
提交回复
热议问题