Entity Framework Indexing ALL foreign key columns

后端 未结 2 555
礼貌的吻别
礼貌的吻别 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: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.

提交回复
热议问题